【问题标题】:How to set background color of HTML element using css properties in JavaScript如何使用 JavaScript 中的 css 属性设置 HTML 元素的背景颜色
【发布时间】:2010-09-05 10:08:55
【问题描述】:

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

【问题讨论】:

    标签: javascript css background-color


    【解决方案1】:
    var element = document.getElementById('element');
    element.style.background = '#FF00AA';
    

    【讨论】:

      【解决方案2】:

      通常,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');
      

      【讨论】:

      • 我想添加颜色显然需要在引号中 element.style.backgroundColor = "color";例如 - element.style.backgroundColor = "orange";很好的答案
      • 在 Selenium 测试中:((IJavaScriptExecutor)WebDriver).ExecuteScript("arguments[0].style.background = 'yellow';", webElement);
      • @Catto 在这种情况下,颜色是函数的参数,因此它不应该用引号引起来。但是,您是对的,通常情况下,如果设置颜色,则 JS 中需要双引号。
      【解决方案3】:

      或者,使用一点 jQuery:

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

      【讨论】:

      • 很可能,因为 OP 要求使用 Javascript ;)
      【解决方案4】:

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

      你的 CSS 显然是这样的:

      .highlight {
          background:#ff00aa;
      }
      

      然后在 JavaScript 中:

      element.className = element.className === 'highlight' ? '' : 'highlight';
      

      【讨论】:

      • 我会说放在哪里很明显 - 在您想要更改的 HTML 之后的任何位置。
      • 这在大多数情况下都是有效的,但在配置中定义颜色(或任何属性)或用户输入的情况下,您不能为每种可能的颜色创建 CSS 类;)
      【解决方案5】:

      将此脚本元素添加到您的正文元素:

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

      【讨论】:

        【解决方案6】:

        亲吻答案:

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

        【讨论】:

        • 上课怎么办?
        • document.getElementByClass('element').style.background = '#DD00DD';
        【解决方案7】:

        你可以使用:

        <script type="text/javascript">
          Window.body.style.backgroundColor = "#5a5a5a";
        </script>
        

        【讨论】:

          【解决方案8】:

          你可以用 JQuery 做到这一点:

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

          【讨论】:

            【解决方案9】:

            你可以使用

            $('#elementID').css('background-color', '#C0C0C0');
            

            【讨论】:

            • 这是 jquery 不是 javascript
            • @vignesh jQuery JavaScript -__-
            • @Novocaine jQuery 是使用 JavaScript 编写的,是的。但除非你包含那个 jQuery 库,否则 $ 仍然无法工作;)
            【解决方案10】:

            var element = document.getElementById('element');
            
            element.onclick = function() {
              element.classList.add('backGroundColor');
              
              setTimeout(function() {
                element.classList.remove('backGroundColor');
              }, 2000);
            };
            .backGroundColor {
                background-color: green;
            }
            &lt;div id="element"&gt;Click Me&lt;/div&gt;

            【讨论】:

              【解决方案11】:

              你可以试试这个

              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

              【讨论】:

              • element.style.background-color 不是有效的 JavaScript。这就是 CSS 属性转换为 CamelCase 的原因。
              【解决方案12】:
              $(".class")[0].style.background = "blue";
              

              【讨论】:

              • 这个问题的正确答案绰绰有余,而这个答案并没有比其他答案更好。
              • 正如 Novocaine 所说,这里有很多答案。但将来请考虑编辑您的帖子,以添加更多关于您的代码的作用以及它为什么会解决问题的解释。一个大部分只包含代码的答案(即使它正在工作)通常不会帮助 OP 理解他们的问题。
              【解决方案13】:
              $("body").css("background","green"); //jQuery
              
              document.body.style.backgroundColor = "green"; //javascript
              

              有这么多方法,我觉得很简单

              Demo On Plunker

              【讨论】:

                【解决方案14】:
                $('#ID / .Class').css('background-color', '#FF6600');
                

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

                【讨论】:

                  【解决方案15】:

                  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
                  

                  【讨论】:

                    【解决方案16】:

                    更改 HTMLElement 的 CSS

                    您可以使用 JavaScript 更改大部分 CSS 属性,使用以下语句:

                    document.querySelector(<selector>).style[<property>] = <new style>
                    

                    其中&lt;selector&gt;&lt;property&gt;&lt;new style&gt; 都是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;
                    }
                    &lt;div class="box"&gt;&lt;/div&gt;

                    改变多个HTMLElement的CSS

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

                    1. 选择带有.querySelectorAll 的元素并将它们解包到带有destructuring syntax 的对象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;
                    }
                    &lt;div class='box'&gt;&lt;/div&gt;

                    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
                    

                    【讨论】:

                      【解决方案17】:

                      一个简单的js就可以解决这个问题:

                      document.getElementById("idName").style.background = "blue";
                      

                      【讨论】:

                        猜你喜欢
                        • 2011-08-31
                        • 1970-01-01
                        • 1970-01-01
                        • 2011-10-24
                        • 2021-03-24
                        • 2021-04-03
                        • 1970-01-01
                        • 1970-01-01
                        • 2012-05-05
                        相关资源
                        最近更新 更多