如何使用JavaScript设置HTML元素的CSS背景颜色?
答案 0 :(得分:147)
通常,CSS属性通过使它们成为没有任何破折号的camelCase而转换为JavaScript。因此background-color
变为backgroundColor
。
function setColor(element, color)
{
element.style.backgroundColor = color;
}
答案 1 :(得分:28)
如果您在CSS中保留所有样式等,并且只是在JavaScript中设置/取消设置类名,您可能会发现您的代码更易于维护。
你的CSS显然会是这样的:
.highlight {
background:#ff00aa;
}
然后在JavaScript中:
element.className = element.className === 'highlight' ? '' : 'highlight';
答案 2 :(得分:23)
var element = document.getElementById('element');
element.style.background = '#FF00AA';
答案 3 :(得分:20)
或者,使用一点点jQuery:
$('#fieldID').css('background-color', '#FF6600');
答案 4 :(得分:7)
将此脚本元素添加到您的body元素:
<body>
<script type="text/javascript">
document.body.style.backgroundColor = "#AAAAAA";
</script>
</body>
答案 5 :(得分:6)
var element = document.getElementById('element');
element.onclick = function() {
element.classList.add('backGroundColor');
setTimeout(function() {
element.classList.remove('backGroundColor');
}, 2000);
};
&#13;
.backGroundColor {
background-color: green;
}
&#13;
<div id="element">Click Me</div>
&#13;
答案 6 :(得分:4)
你可以用JQuery做到这一点:
$(".class").css("background","yellow");
答案 7 :(得分:4)
你可以试试这个
var element = document.getElementById('element_id');
element.style.backgroundColor = "color or color_code";
实施例
var element = document.getElementById('firstname');
element.style.backgroundColor = "green";//Or #ff55ff
答案 8 :(得分:3)
KISS答案:
document.getElementById('element').style.background = '#DD00DD';
答案 9 :(得分:3)
您可以使用:
<script type="text/javascript">
Window.body.style.backgroundColor = "#5a5a5a";
</script>
答案 10 :(得分:3)
$('#ID / .Class').css('background-color', '#FF6600');
通过使用jquery,我们可以定位元素的类或Id以应用css背景或任何其他样式
答案 11 :(得分:2)
$("body").css("background","green"); //jQuery
document.body.style.backgroundColor = "green"; //javascript
有很多方法我觉得这很容易和简单
答案 12 :(得分:1)
你可以使用
$('#elementID').css('background-color', '#C0C0C0');
答案 13 :(得分:0)
使用Javascript:
document.getElementById("ID").style.background = "colorName"; //JS ID
document.getElementsByClassName("ClassName")[0].style.background = "colorName"; //JS Class
Jquery的:
$('#ID/.className').css("background","colorName") // One style
$('#ID/.className').css({"background":"colorName","color":"colorname"}); //Multiple style
答案 14 :(得分:0)
HTMLElement
您可以使用JavaScript更改大多数CSS属性,请使用以下语句:
document.querySelector(<selector>).style[<property>] = <new style>
其中<selector>
,<property>
,<new style>
都是String
个对象。
通常,style属性的名称与CSS中使用的实际名称相同。但是,只要有一个单词,就会出现这种情况:例如,background-color
会随backgroundColor
更改。
以下语句将#container
的背景设置为红色:
documentquerySelector('#container').style.background = 'red'
这是一个快速演示,每隔0.5秒改变一次盒子的颜色:
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
想象一下,您希望将CSS样式应用于多个元素,例如,使用类名box
lightgreen
制作所有元素的背景颜色。然后你可以:
选择包含.querySelectorAll
的元素,并使用destructuring syntax在对象Array
中展开它们:
const elements = [...document.querySelectorAll('.box')]
使用.forEach
循环遍历数组并将更改应用于每个元素:
elements.forEach(element => element.style.background = 'lightgreen')
以下是演示:
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>
如果您想多次更改元素的多个样式属性,可以考虑使用另一种方法:改为将此元素链接到另一个类。
假设您可以预先在CSS中准备样式,您可以通过访问元素的classList
并调用toggle
函数来切换类:
document.querySelector('.box').classList.toggle('orange')
.box {
width: 100px;
height: 100px;
}
.orange {
background: orange;
}
<div class='box'></div>
以下是完整列表:
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
答案 15 :(得分:-1)
$(".class")[0].style.background = "blue";