在 JavaScript 中更改 DIV 类样式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16460315/
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-10-27 04:44:40  来源:igfitidea点击:

Changing a DIV class style in JavaScript

javascripthtmlcss

提问by Garfield Punchbag

i can do this to change the style of a div ID...

我可以这样做来更改 div ID 的样式...

document.getElementById('test').style.display = "none";

why can't i do this to do the same thing to a class?

为什么我不能这样做对一个班级做同样的事情?

document.getElementsByClassName('egg').style.display = "none";

How do I change the style of a class?

如何更改班级风格?

Thanks

谢谢

回答by Monokh

document.getElementsByClassNamereturns a list of elements with the class specified. You can set the display to none of the first element:

document.getElementsByClassName返回具有指定类的元素列表。您可以将显示设置为没有第一个元素:

document.getElementsByClassName('egg')[0].style.display = "none";

Or loop through the list and set each to the desired effect:

或者循环遍历列表并将每个设置为所需的效果:

var eggs = document.getElementsByClassName('egg');
for(var i = 0; i < eggs.length; i++) { 
  eggs[i].style.display='none'
}

回答by Gurpreet Singh

This should work:

这应该有效:

 var elements = document.getElementsByClassName('egg');
    for(var i = 0, length = elements.length; i < length; i++) {
         elements[i].style.display = 'none';
    }
}

Note: elementsis an array, this code loops through it and sets each element style to none.

注意:elements是一个数组,此代码循环遍历它并将每个元素样式设置为无。

回答by Parv Sharma

The return value of document.getElementsByClassName('egg')is an array.

的返回值document.getElementsByClassName('egg')是一个数组。

document.getElementsByClassName('egg').forEach(function(b) {
        b.style.display = "none";
    })

回答by dreamweiver

<script language="javascript">
function assignStyle() {
  var chks = document.getElementsByClassName('myClass');
  for (var i = 0; i < chks.length; i++) {
    chks[i].style.display = 'none';

  }

 }
 </script>

Happy Coding :)

快乐编码:)

回答by Ganesh Bora

insted of doing all this stuff simply use jquery $('.myClass').css({ ...Your CSS properties here... });

不需要做所有这些事情,只需使用 jquery $('.myClass').css({ ...你的 CSS 属性在这里... });