Answers:
通常,将CSS属性转换为JavaScript的方式是将它们变成驼峰式(CamelCase)而没有任何破折号。如此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');
如果将所有样式保留在CSS中,而仅在JavaScript中设置/取消设置类名,则可能会发现代码更易于维护。
您的CSS显然是这样的:
.highlight {
background:#ff00aa;
}
然后在JavaScript中:
element.className = element.className === 'highlight' ? '' : 'highlight';
或者,使用一些jQuery:
$('#fieldID').css('background-color', '#FF6600');
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的原因。
吻答案:
document.getElementById('element').style.background = '#DD00DD';
document.getElementByClass('element').style.background = '#DD00DD';
$("body").css("background","green"); //jQuery
document.body.style.backgroundColor = "green"; //javascript
有很多方法,我认为这非常简单
$('#ID / .Class').css('background-color', '#FF6600');
通过使用jQuery,我们可以将元素的类或Id作为目标以应用css背景或任何其他样式
您可以使用
$('#elementID').css('background-color', '#C0C0C0');
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
您可以使用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.5s更改盒子的颜色:
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
然后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";
$(".class")[0].style.background = "blue";