更改或一次交换多个HTML元素的CSS
我有大约100 <跨度类=foo的>
100 <跨度类=酒吧>
100 <跨度类=巴兹>
我的文档中的标签。我需要实现在JavaScript中执行以下操作:
I have about 100 <span class="foo">
, 100 <span class="bar">
and 100 <span class="baz">
tags in my document. I need to implement the following operations in JavaScript:
- 更改背景都FOOS红色,所有的酒吧,以绿色,所有bazes蓝色。
- 更改背景都FOOS绿色,所有的酒吧为蓝色,所有bazes红色。
- 更改背景都FOOS为蓝色,所有的酒吧为红色,所有bazes绿色。
我就干脆打电话约1000倍这些操作,所以我想,以避免追加的溶液&LT;风格&GT;
标签&LT;头方式&gt;
每次我做手术
I will call these operations about 1000 times altogether, so I'd like to avoid a solution which appends a <style>
tag to the <head>
each time I do an operation.
有什么比遍历所有的&LT简单或更快,更好;跨度&GT;
与元素document.getElementsByTagName('跨')
,改变或追加到每个元素的 .className
DOM属性?
Is there something simpler or faster or better than iterating over all <span>
elements with document.getElementsByTagName('span')
, and changing or appending to the .className
DOM properties for each element?
最简单的方法是使用CSS来做到这一点,而不是改变元素的类名。考虑下面的标记和CSS。
The simplest way is to use CSS to do this, rather than changing the element classnames. Consider the following markup and CSS.
.normal .foo{
background-color: #0f0;
}
.alternate .foo {
background-color: #f00;
}
<body class="normal">
<span class="foo">hello</span>
<span class="bar">hello</span>
<span class="baz">hello</span>
</body>
您可以简单地使用JavaScript从正常的身体改变类名交替,来实现对包含.foo元素的颜色变化。更多的规则将设置栏和巴兹颜色。
You can simply use javascript to change the classname on the body from normal to alternate, to implement the color change on .foo elements. More rules will set colors for bar and baz.
document.getElementsByTagName('body')[0].className = 'alternate';