更改或一次交换多个HTML元素的CSS [英] Change or swap the CSS of multiple HTML elements at once

查看:135
本文介绍了更改或一次交换多个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';

这篇关于更改或一次交换多个HTML元素的CSS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆