使用 DOM 样式通过 Javascript 获取或更改 CSS 类属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19353331/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 00:42:03  来源:igfitidea点击:

Getting or changing CSS class property with Javascript using DOM style

javascriptcssdom

提问by jgrant

My objective is to change the background color of a columns in a table without addressing each data entry individually by Id or Name. I know there are several ways to do this, and I've tried 3 to be exact, and I'm having problems with each. For the sake of simplicity and clarity, In this question, I'm asking how to successfully do it using the element.style.backgroundColorobject in the DOM. Here's my HTML:

我的目标是更改表中列的背景颜色,而无需按 Id 或 Name 单独处理每个数据条目。我知道有几种方法可以做到这一点,确切地说,我已经尝试了 3 种方法,但每种方法都存在问题。为了简单和清晰起见,在这个问题中,我询问如何使用DOM 中的element.style.backgroundColor对象成功地做到这一点。这是我的 HTML:

    <!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" type="text/css" href="tester.css">
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
        <script type="text/javascript" src="tester.js"></script> 
    </head>
    <body>
    <button type="button" onClick="testerFunction()">Test</button>
        <table>
            <tr>
                <th class="col1">Column 1 Header</th>
                <th class="col2">Column 2 Header</th>
            </tr>
            <tr>
                <td class="col1">R1 C1</td>
                <td class="col2">R1 C2</td>
            </tr>
            <tr>
                <td class="col1">R2 C1</td>
                <td class="col2">R2 C2</td>
            </tr>
        </table>
     </body>
 </html>

My CSS file:

我的 CSS 文件:

.col1{
    background-color:lime;  
}

And my Javascript file:

还有我的 Javascript 文件:

function testerFunction() {
    alert (document.getElementsByClassName('.col1').style.backgroundColor);  
}

When I run it I get roughly the same error in IE, Firefox, and Chrome:

当我运行它时,我在 IE、Firefox 和 Chrome 中得到大致相同的错误:

cannot read property 'backgroundColor' of Undefined.

无法读取未定义的属性“backgroundColor”。

I have a feeling it has something to do with the data type returned by the document.getElementsByClassNameDOM object. The referenced website says it returns an HTMLcollection. Other places I've found says it returns a "list" of elements. I tried making an array and assigning the result to the array and accessing each element in the array with a loop, but got the same error at the same place. It might be that I just don't know how to handle a, "collection." At any rate, I was expecting, "lime" or the hex or rgb equivalent because that's what I defined in the CSS file. I want to be able to change it with Javascript. Any help would be much appreciated. Thanks!

我有一种感觉,它与document.getElementsByClassNameDOM 对象返回的数据类型有关。引用的网站说它返回一个 HTMLcollection。我发现的其他地方说它返回元素的“列表”。我尝试创建一个数组并将结果分配给数组并使用循环访问数组中的每个元素,但在同一个地方得到了相同的错误。可能是我只是不知道如何处理一个“集合”。无论如何,我期待“lime”或等效的十六进制或 rgb,因为这是我在 CSS 文件中定义的内容。我希望能够用 Javascript 改变它。任何帮助将非常感激。谢谢!

EDIT: Added arguments to Shylo Hana's Answer to make it more modular

编辑:为 Shylo Hana 的答案添加了参数以使其更加模块化

function testerFunction() {
    changeColumnColor('col1','blue');
}
function changeColumnColor(column,color) {
    var cols = document.getElementsByClassName(column);
    for(i=0; i<cols.length; i++) {
      cols[i].style.backgroundColor = color;
    }
}

回答by Shylo Hana

As mentioned by Quynh Nguyen, you don't need the '.' in the className. However - document.getElementsByClassName('col1') will return an array of objects.

正如 Quynh Nguyen 所提到的,您不需要 '.' 在类名中。但是 - document.getElementsByClassName('col1') 将返回一个对象数组。

This will return an "undefined" value because an array doesn't have a class. You'll still need to loop through the array elements...

这将返回一个“未定义”值,因为数组没有类。您仍然需要遍历数组元素...

function changeBGColor() {
  var cols = document.getElementsByClassName('col1');
  for(i = 0; i < cols.length; i++) {
    cols[i].style.backgroundColor = 'blue';
  }
}

回答by Infinity

You don't need to add '.' in your class name. This will do

您不需要添加“。” 在您的班级名称中。这会做

document.getElementsByClassName('col1')

Additionally, since you haven't define the background color via javascript, you won't able to call it directly. You have to use window.getComputedStyle() or jquery to achieve what you are trying to do above.

此外,由于您尚未通过 javascript 定义背景颜色,因此您将无法直接调用它。您必须使用 window.getComputedStyle() 或 jquery 来实现您在上面尝试执行的操作。

Here is a working example

这是一个工作示例

http://jsfiddle.net/J9LU8/

http://jsfiddle.net/J9LU8/

回答by Johann Echavarria

Maybe better document.querySelectorAll(".col1")because getElementsByClassNamedoesn't works in IE 8 and querySelectorAlldoes (althought CSS2 selectors only).

也许更好,document.querySelectorAll(".col1")因为getElementsByClassName它在 IE 8 中querySelectorAll不起作用,并且(虽然仅适用于CSS2 选择器)。

https://developer.mozilla.org/en-US/docs/Web/API/document.getElementsByClassNamehttps://developer.mozilla.org/en-US/docs/Web/API/Document.querySelectorAll

https://developer.mozilla.org/en-US/docs/Web/API/document.getElementsByClassName https://developer.mozilla.org/en-US/docs/Web/API/Document.querySelectorAll

回答by Jules Bartow

Nice. Thank you. Worked For Me.

好的。谢谢你。为我工作。

Not sure why you loaded jQuery though. It's not used. Some of us still use dial up modems and satellite with bandwidth limitations. Less is more betterer.

不知道你为什么加载 jQuery。它没有被使用。我们中的一些人仍然使用具有带宽限制的拨号调制解调器和卫星。越少越好。

<script>
        function showAnswers(){
          var cols = document.getElementsByClassName('Answer');
          for(i=0; i<cols.length; i++) {
            cols[i].style.backgroundColor = 'lime';
            cols[i].style.width = '50%';
            cols[i].style.borderRadius = '6px';         
            cols[i].style.padding = '10px';
            cols[i].style.border = '1px green solid';
            }
        }
        function hideAnswers(){
          var cols = document.getElementsByClassName('Answer');
          for(i=0; i<cols.length; i++) {
            cols[i].style.backgroundColor = 'transparent';
            cols[i].style.width = 'inheret';
            cols[i].style.borderRadius = '0';
            cols[i].style.padding = '0';
            cols[i].style.border = 'none';          
          }
        }
    </script>

回答by RealNeo

I think this is not the best way, but in my cases other methods did not work.

我认为这不是最好的方法,但在我的情况下,其他方法不起作用。

stylesheet = document.styleSheets[0]
stylesheet.insertRule(".have-border { border: 1px solid black;}", 0);

Example from https://www.w3.org/wiki/Dynamic_style_-_manipulating_CSS_with_JavaScript

来自https://www.w3.org/wiki/Dynamic_style_-_manipulating_CSS_with_JavaScript 的示例