Làm cách nào để đặt màu nền CSS của một phần tử HTML bằng JavaScript?
Làm cách nào để đặt màu nền CSS của một phần tử HTML bằng JavaScript?
Câu trả lời:
Nói chung, các thuộc tính CSS được chuyển đổi sang JavaScript bằng cách biến chúng thành camelCase mà không có bất kỳ dấu gạch ngang nào. Vì vậy, background-color
trở thành backgroundColor
.
function setColor(element, color)
{
element.style.backgroundColor = color;
}
// where el is the concerned element
var el = document.getElementById('elementId');
setColor(el, 'green');
Bạn có thể thấy mã của mình dễ bảo trì hơn nếu bạn giữ tất cả các kiểu của mình, v.v. trong CSS và chỉ đặt / bỏ đặt tên lớp trong JavaScript.
CSS của bạn rõ ràng sẽ giống như:
.highlight {
background:#ff00aa;
}
Sau đó, trong JavaScript:
element.className = element.className === 'highlight' ? '' : 'highlight';
Hoặc, sử dụng một chút jQuery:
$('#fieldID').css('background-color', '#FF6600');
Thêm phần tử tập lệnh này vào phần tử nội dung của bạn:
<body>
<script type="text/javascript">
document.body.style.backgroundColor = "#AAAAAA";
</script>
</body>
var element = document.getElementById('element');
element.onclick = function() {
element.classList.add('backGroundColor');
setTimeout(function() {
element.classList.remove('backGroundColor');
}, 2000);
};
.backGroundColor {
background-color: green;
}
<div id="element">Click Me</div>
Bạn có thể thử cái này
var element = document.getElementById('element_id');
element.style.backgroundColor = "color or color_code";
Thí dụ.
var element = document.getElementById('firstname');
element.style.backgroundColor = "green";//Or #ff55ff
element.style.background-color
JavaScript không hợp lệ. Đó là lý do tại sao các thuộc tính CSS được chuyển đổi thành CamelCase.
KISS trả lời:
document.getElementById('element').style.background = '#DD00DD';
document.getElementByClass('element').style.background = '#DD00DD';
$("body").css("background","green"); //jQuery
document.body.style.backgroundColor = "green"; //javascript
rất nhiều cách ở đó tôi nghĩ nó rất dễ dàng và đơn giản
$('#ID / .Class').css('background-color', '#FF6600');
Bằng cách sử dụng jquery, chúng ta có thể nhắm mục tiêu lớp hoặc Id của phần tử để áp dụng nền css hoặc bất kỳ kiểu dáng nào khác
bạn có thể dùng
$('#elementID').css('background-color', '#C0C0C0');
Javascript:
document.getElementById("ID").style.background = "colorName"; //JS ID
document.getElementsByClassName("ClassName")[0].style.background = "colorName"; //JS Class
Truy vấn:
$('#ID/.className').css("background","colorName") // One style
$('#ID/.className').css({"background":"colorName","color":"colorname"}); //Multiple style
HTMLElement
Bạn có thể thay đổi hầu hết các thuộc tính CSS bằng JavaScript, sử dụng câu lệnh sau:
document.querySelector(<selector>).style[<property>] = <new style>
nơi <selector>
, <property>
, <new style>
là tất cả String
các đối tượng.
Thông thường, thuộc tính style sẽ có cùng tên với tên thực được sử dụng trong CSS. Nhưng bất cứ khi nào có nhiều hơn một từ đó, nó sẽ là trường hợp lạc đà: ví dụ: background-color
được thay đổi bằngbackgroundColor
.
Câu lệnh sau sẽ đặt nền của #container
thành màu đỏ:
documentquerySelector('#container').style.background = 'red'
Dưới đây là một bản demo nhanh chóng thay đổi màu của hộp sau mỗi 0,5 giây:
colors = ['rosybrown', 'cornflowerblue', 'pink', 'lightblue', 'lemonchiffon', 'lightgrey', 'lightcoral', 'blueviolet', 'firebrick', 'fuchsia', 'lightgreen', 'red', 'purple', 'cyan']
let i = 0
setInterval(() => {
const random = Math.floor(Math.random()*colors.length)
document.querySelector('.box').style.background = colors[random];
}, 500)
.box {
width: 100px;
height: 100px;
}
<div class="box"></div>
HTMLElement
Hãy tưởng tượng bạn muốn áp dụng các kiểu CSS cho nhiều phần tử, ví dụ: tạo màu nền của tất cả các phần tử có tên lớp box
lightgreen
. Sau đó bạn có thể:
chọn các phần tử có .querySelectorAll
và mở chúng trong một đối tượng Array
bằng cú pháp hủy cấu trúc :
const elements = [...document.querySelectorAll('.box')]
lặp qua mảng với .forEach
và áp dụng thay đổi cho từng phần tử:
elements.forEach(element => element.style.background = 'lightgreen')
Đây là bản demo:
const elements = [...document.querySelectorAll('.box')]
elements.forEach(element => element.style.background = 'lightgreen')
.box {
height: 100px;
width: 100px;
display: inline-block;
margin: 10px;
}
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
Nếu bạn muốn thay đổi nhiều thuộc tính kiểu của một phần tử nhiều lần, bạn có thể cân nhắc sử dụng một phương pháp khác: liên kết phần tử này với một lớp khác.
Giả sử bạn có thể chuẩn bị trước các kiểu trong CSS, bạn có thể chuyển đổi các lớp bằng cách truy cập vào classList
phần tử và gọi toggle
hàm:
document.querySelector('.box').classList.toggle('orange')
.box {
width: 100px;
height: 100px;
}
.orange {
background: orange;
}
<div class='box'></div>
Đây là danh sách đầy đủ:
alignContent
alignItems
alignSelf
animation
animationDelay
animationDirection
animationDuration
animationFillMode
animationIterationCount
animationName
animationTimingFunction
animationPlayState
background
backgroundAttachment
backgroundColor
backgroundImage
backgroundPosition
backgroundRepeat
backgroundClip
backgroundOrigin
backgroundSize</a></td>
backfaceVisibility
borderBottom
borderBottomColor
borderBottomLeftRadius
borderBottomRightRadius
borderBottomStyle
borderBottomWidth
borderCollapse
borderColor
borderImage
borderImageOutset
borderImageRepeat
borderImageSlice
borderImageSource
borderImageWidth
borderLeft
borderLeftColor
borderLeftStyle
borderLeftWidth
borderRadius
borderRight
borderRightColor
borderRightStyle
borderRightWidth
borderSpacing
borderStyle
borderTop
borderTopColor
borderTopLeftRadius
borderTopRightRadius
borderTopStyle
borderTopWidth
borderWidth
bottom
boxShadow
boxSizing
captionSide
clear
clip
color
columnCount
columnFill
columnGap
columnRule
columnRuleColor
columnRuleStyle
columnRuleWidth
columns
columnSpan
columnWidth
counterIncrement
counterReset
cursor
direction
display
emptyCells
filter
flex
flexBasis
flexDirection
flexFlow
flexGrow
flexShrink
flexWrap
content
fontStretch
hangingPunctuation
height
hyphens
icon
imageOrientation
navDown
navIndex
navLeft
navRight
navUp>
cssFloat
font
fontFamily
fontSize
fontStyle
fontVariant
fontWeight
fontSizeAdjust
justifyContent
left
letterSpacing
lineHeight
listStyle
listStyleImage
listStylePosition
listStyleType
margin
marginBottom
marginLeft
marginRight
marginTop
maxHeight
maxWidth
minHeight
minWidth
opacity
order
orphans
outline
outlineColor
outlineOffset
outlineStyle
outlineWidth
overflow
overflowX
overflowY
padding
paddingBottom
paddingLeft
paddingRight
paddingTop
pageBreakAfter
pageBreakBefore
pageBreakInside
perspective
perspectiveOrigin
position
quotes
resize
right
tableLayout
tabSize
textAlign
textAlignLast
textDecoration
textDecorationColor
textDecorationLine
textDecorationStyle
textIndent
textOverflow
textShadow
textTransform
textJustify
top
transform
transformOrigin
transformStyle
transition
transitionProperty
transitionDuration
transitionTimingFunction
transitionDelay
unicodeBidi
userSelect
verticalAlign
visibility
voiceBalance
voiceDuration
voicePitch
voicePitchRange
voiceRate
voiceStress
voiceVolume
whiteSpace
width
wordBreak
wordSpacing
wordWrap
widows
writingMode
zIndex
Một js đơn giản có thể giải quyết điều này:
document.getElementById("idName").style.background = "blue";
$(".class")[0].style.background = "blue";