如何使用 javascript 修改元素的 CSS class(翻译 70%)
发布在stackoverflow 热门 javascript 问答2013年12月5日view:27585
在文章任何区域双击击即可给文章添加【评注】!浮到评注点上可以查看详情。

问题Change an element's CSS class with JavaScript

如何在 onClick 事件中修改 html 元素的 css class属性?

回答http://stackoverflow.com/a/196038/343194

简单的跨浏览器添加和删除 class

在标准的 javascript 中,选择一个元素使用 document.getElementById("Id"), which is what the following examples use - you can of course obtain elements in other ways, and in the right situation may simply use this instead - however, going into detail on this is beyond the scope of the answer.

修改元素的“所有”的 class

用新的 class 替换掉原有的所有 class,可以设置 className 属性:

document.getElementById("MyElement").className = "MyClass";

(如果想替换为多个 class,可以使用空格分隔。)

为元素添加新的 class

如果想添加一个新的 class,并保留所有原有的 class,可以:

document.getElementById("MyElement").className += " MyClass";

(注意 MyClass 前面的空格。)

删除元素的某个 class

如果要删除某个元素的单个 class 属性,而不影响其它 class,可以使用正则表达式进行替换:

document.getElementById("MyElement").className =
   document.getElementById("MyElement").className.replace
      ( /(?:^|\s)MyClass(?!\S)/g , '' )
/* code wrapped for readability - above is all one statement */

正则表达式解释:

(?:^|\s) # 匹配字符串开始,或者单个空白字符

MyClass  # 需要移除的 class 值

(?!\S)   # negative lookahead to verify the above is the whole classname
         # ensures there is no non-space character following
         # (i.e. must be end of string or a space)

g 可以进行全局匹配。

检查元素是否已经存在某 class

下面的正则表达式用来检查元素是否已经存在某个 class。

if ( document.getElementById("MyElement").className.match(/(?:^|\s)MyClass(?!\S)/) )

Assigning these actions to onclick events:

Whilst it is possible to write JavaScript directly inside the HTML event attributes (such as onclick="this.className+=' MyClass'") this is not recommended behaviour. Especially on larger applications, more maintainable code is achieved by separating HTML markup from JS interaction logic.

The first step to achieving this is by creating a function, and calling the function in the onclick attribute, for example:

<script type="text/javascript">
    function changeClass()
    {
        // code examples from above
    }
</script>
...
<button onclick="changeClass()">My Button</button>

(It is not required to have this code in script tags, this is simply for brevity of example, and including the JS in a distinct file may be more appropriate.)

The second step is to move the onclick event out of the HTML and into JavaScript, for example using addEventListener

<script type="text/javascript">
    function changeClass()
    {
        // code examples from above
    }

    window.onload = function()
    {
        document.getElementById("MyElement").addEventListener( 'click' , changeClass );
    }
</script>
...
<button id="MyElement">My Button</button>

(Note that the window.onload part is required so that the contents of that function are executed after the HTML has finished loading - without this, the MyElement might not exist when the JS is called, so that line would fail.)


JavaScript Frameworks and Libraries

The above code is all in standard JavaScript, however it is common practise to use either a framework or a library to simplify common tasks, as well as benefit from fixed bugs and edge cases that you might not think of when writing your code.

Whilst some people consider it overkill to add a ~50KB framework for simply changing a class, if you are doing any substantial amount of JavaScript work, or anything that might have unusual cross-browser behaviour, it is well worth considering.

(Very roughly, a library is a set of tools designed for a specific task, whilst a framework generally contains multiple libraries and performs a complete set of duties.)

The examples above have been reproduced below using jQuery, probably the most commonly used JavaScript library (though there are others worth investigating too).

(Note that $ here is the jQuery object.)

Changing Classes with jQuery:

$('#MyElement').addClass('MyClass');

$('#MyElement').removeClass('MyClass');

if ( $('#MyElement').hasClass('MyClass') )

In addition, jQuery provides a shortcut for adding a class if it doesn't apply, or removing a class that does:

$('#MyElement').toggleClass('MyClass');


Assigning a function to a click event with jQuery:

$('#MyElement').click(changeClass);

or, without needing an id:

$(':button:contains(My Button)').click(changeClass);


HTML5 Techniques for changing classes

Modern browsers have added classList which provides methods to make it easier to manipulate classes without needing a library:

document.getElementById("MyElement").classList.add('class');

document.getElementById("MyElement").classList.remove('class');

if ( document.getElementById("MyElement").classList.contains('class') )

document.getElementById("MyElement").classList.toggle('class');

Unfortunately, these do not work in Internet Explorer prior to v10, though there is a shim to add support for it to IE8 and IE9, available from this page.

评论
发表评论
暂无评论
WRITTEN BY
justjavac(迷渡)
☑辍学生 ☑极客 ☑码农 正在出版「代码之谜」,正在翻译「Javascript Quirks」。 http://justjavac.com
TA的新浪微博
PUBLISHED IN
stackoverflow 热门 javascript 问答

翻译 stackoverflow 上面的热门 javascript 问答。

我的收藏