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

有帮助吗?

解决方案

一般来说,CSS 属性通过使用驼峰命名法(不带任何破折号)来转换为 JavaScript。所以 background-color 变成 backgroundColor.

function setColor(element, color)
{
    element.style.backgroundColor = color;
}

其他提示

如果保留所有样式等,您可能会发现您的代码更易于维护。在 CSS 中,只需在 JavaScript 中设置/取消设置类名。

你的 CSS 显然会是这样的:

.highlight {
    background:#ff00aa;
}

然后在 JavaScript 中:

element.className = element.className === 'highlight' ? '' : 'highlight';
var element = document.getElementById('element');
element.style.background = '#FF00AA';

或者,使用一点 jQuery:

$('#fieldID').css('background-color', '#FF6600');

将此脚本元素添加到您的 body 元素中:

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

你可以试试这个

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

您可以使用 JQuery 来做到这一点:

$(".class").css("background","yellow");

吻 答案:

document.getElementById('element').style.background = '#DD00DD';

您可以使用:

  <script type="text/javascript">
     Window.body.style.backgroundColor = "#5a5a5a";
  </script>
$('#ID / .Class').css('background-color', '#FF6600');

通过使用 jquery,我们可以定位元素的类或 Id 以应用 css 背景或任何其他样式

$("body").css("background","green"); //jQuery

document.body.style.backgroundColor = "green"; //javascript

有很多方法我认为这非常容易和简单

Plunker 演示

您可以使用

$('#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

更改 a 的 CSS HTMLElement

您可以使用 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>


改变多个CSS HTMLElement

想象一下,您想将 CSS 样式应用于多个元素,例如,使用类名称为所有元素设置背景颜色 box lightgreen. 。然后你可以:

  1. 选择元素 .querySelectorAll 并将它们展开在一个对象中 Array解构语法:

    const elements = [...document.querySelectorAll('.box')]
    
  2. 循环数组 .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>


JavaScript 中的 CSS 属性列表

以下是完整列表:

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
$(".class")[0].style.background = "blue";
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top