如何在 JavaScript 中使用 css 属性设置 HTML 元素的背景颜色

如何在 JavaScript 中使用 css 设置 HTML 元素的背景颜色?

184591 次浏览
var element = document.getElementById('element');
element.style.background = '#FF00AA';

一般来说,CSS 属性通过不加任何破折号的 camelCase 转换成 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';

将这个 script 元素添加到 body 元素:

<body>
<script type="text/javascript">
document.body.style.backgroundColor = "#AAAAAA";
</script>
</body>

KISS 回答:

document.getElementById('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

JSFIDDLE

$(".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>


Changing CSS of multiple HTMLElement

Imagine you would like to apply CSS styles to more than one element, for example, make the background color of all elements with the class name box lightgreen. Then you can:

  1. select the elements with .querySelectorAll and unwrap them in an object Array with the destructuring syntax:

    const elements = [...document.querySelectorAll('.box')]
    
  2. loop over the array with .forEach and apply the change to each element:

    elements.forEach(element => element.style.background = 'lightgreen')
    

Here is the 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>


另一种方法

如果希望多次更改元素的多个样式属性,可以考虑使用另一种方法: 将此元素链接到另一个类。

假设您可以事先在 CSS 中准备样式,您可以通过访问元素的 classList并调用 toggle函数来切换类:

document.querySelector('.box').classList.toggle('orange')
.box {
width: 100px;
height: 100px;
}


.orange {
background: orange;
}
<div class='box'></div>


List of CSS properties in JavaScript

Here is the complete list:

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";