简体   繁体   English

使用JavaScript一次更改具有相同类名的多个元素的样式?

[英]Changing multiple elements' styles with a same class name at once with JavaScript?

I have a bunch of divs with different combinations of classes in each (eg "a A", "ab", "b A", "b" etc.). 我有一堆div,每个div都有不同的类组合(例如“a A”,“ab”,“b A”,“b”等)。

With a press of a button, I need to change the styles of, for example, all elements which have the class A (not only 'A', but must include it. Eg both "d A" and "A" would work) 只需按一下按钮,我就需要改变所有具有A类的元素的样式(不仅是'A',而且必须包含它。例如“d A”和“A”都可以使用)

I have tried 我努力了

document.getElementsByClassName('a A').style.background = "#f00"; document.getElementsByClassName('a A')。style.background =“#f00”;

but it didn't work. 但它不起作用。 The console says that it can't set a style for element 'undefined', so I guess it doesn't get what I need with getElementsByClassName(); 控制台说它不能为元素'undefined'设置样式,所以我猜它不能得到我需要的getElementsByClassName(); .

The DOM methods that getElementsBySomething (plural), as opposed to ones which getElementBySomething return a NodeList , not an element. getElementsBySomething (复数)的DOM方法,而不是getElementBySomething返回NodeList的DOM方法,而不是元素。 NodeLists are Array-like objects. NodeLists是类似于Array的对象。

You have to loop over it and change each element in turn if you take that approach. 如果你采取这种方法,你必须循环它并依次改变每个元素。 Most libraries have shortcut methods to do that for you. 大多数库都有快捷方法为您完成。

eg for YUI 3: 例如对于YUI 3:

Y.all('.foo').setStyle('background', '#f00');

or jQuery 或jQuery

jQuery('.foo').css('background', '#f00');

An alternative approach would be to modify the stylesheet itself with JavaScript . 另一种方法是使用JavaScript修改样式表本身

A third option would be to set up your changed styles in advance, using a descendent selector such as: 第三种选择是使用后代选择器提前设置更改的样式,例如:

.foo { /* something */ }
body.bar .foo { /* something else */ }

And then 接着

document.body.className += " bar";

to activate the alternative styling. 激活替代样式。

You should try using a library like jQuery that allows you to use CSS selectors. 您应该尝试使用像jQuery这样的库,它允许您使用CSS选择器。 Then you would be able to do 那你就可以做到

$('.a,.A').css("background", "#f00");

You could even change multiple styles at once with multiple elements 您甚至可以使用多个元素一次更改多个样式

$('.a,.A').css({"background": "#f00", "color": "#000"});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM