【发布时间】:2010-09-05 10:08:55
【问题描述】:
如何在 JavaScript 中使用 css 设置 HTML 元素的背景颜色?
【问题讨论】:
标签: javascript css background-color
如何在 JavaScript 中使用 css 设置 HTML 元素的背景颜色?
【问题讨论】:
标签: javascript css background-color
var element = document.getElementById('element');
element.style.background = '#FF00AA';
【讨论】:
通常,CSS 属性转换为 JavaScript,方法是使它们成为不带任何破折号的驼峰式。所以background-color 变成了backgroundColor。
function setColor(element, color)
{
element.style.backgroundColor = color;
}
// where el is the concerned element
var el = document.getElementById('elementId');
setColor(el, 'green');
【讨论】:
或者,使用一点 jQuery:
$('#fieldID').css('background-color', '#FF6600');
【讨论】:
如果您将所有样式等保留在 CSS 中,并且只在 JavaScript 中设置/取消设置类名,您可能会发现您的代码更易于维护。
你的 CSS 显然是这样的:
.highlight {
background:#ff00aa;
}
然后在 JavaScript 中:
element.className = element.className === 'highlight' ? '' : 'highlight';
【讨论】:
将此脚本元素添加到您的正文元素:
<body>
<script type="text/javascript">
document.body.style.backgroundColor = "#AAAAAA";
</script>
</body>
【讨论】:
亲吻答案:
document.getElementById('element').style.background = '#DD00DD';
【讨论】:
document.getElementByClass('element').style.background = '#DD00DD';
你可以使用:
<script type="text/javascript">
Window.body.style.backgroundColor = "#5a5a5a";
</script>
【讨论】:
你可以用 JQuery 做到这一点:
$(".class").css("background","yellow");
【讨论】:
你可以使用
$('#elementID').css('background-color', '#C0C0C0');
【讨论】:
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>
【讨论】:
你可以试试这个
var element = document.getElementById('element_id');
element.style.backgroundColor = "color or color_code";
示例。
var element = document.getElementById('firstname');
element.style.backgroundColor = "green";//Or #ff55ff
【讨论】:
element.style.background-color 不是有效的 JavaScript。这就是 CSS 属性转换为 CamelCase 的原因。
$(".class")[0].style.background = "blue";
【讨论】:
$("body").css("background","green"); //jQuery
document.body.style.backgroundColor = "green"; //javascript
有这么多方法,我觉得很简单
【讨论】:
$('#ID / .Class').css('background-color', '#FF6600');
通过使用 jquery,我们可以定位元素的类或 Id 以应用 css 背景或任何其他样式
【讨论】:
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
【讨论】:
HTMLElement 的 CSS
您可以使用 JavaScript 更改大部分 CSS 属性,使用以下语句:
document.querySelector(<selector>).style[<property>] = <new style>
其中<selector>、<property>、<new style> 都是String 对象。
通常,样式属性的名称与 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
假设您想将 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
【讨论】:
一个简单的js就可以解决这个问题:
document.getElementById("idName").style.background = "blue";
【讨论】: