如何使用 JavaScript 更改元素的类? [英] How can I change an element's class with JavaScript?

查看:32
本文介绍了如何使用 JavaScript 更改元素的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何更改 HTML 元素的类以响应 onclick 或任何其他使用 JavaScript 的事件?

How can I change the class of an HTML element in response to an onclick or any other events using JavaScript?

推荐答案

用于更改类的现代 HTML5 技术

现代浏览器添加了classList 提供的方法可以更轻松地操作类而无需库:

Modern 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('MyClass');

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

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

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

不幸的是,这些在 v10 之前的 Internet Explorer 中不起作用,尽管有一个 shim 将其支持添加到 IE8 和 IE9,可从 此页面获得.不过,它得到越来越多的支持.

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. It is, though, getting more and more supported.

选择元素的标准 JavaScript 方法是使用 document.getElementById("Id"),就是下面例子中用到的——当然你也可以通过其他方式获取元素,在合适的情况下可以简单地使用this 相反 - 但是,对此进行详细讨论超出了答案的范围.

The standard JavaScript way to select an element is using 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.

要用一个或多个新类替换所有现有类,请设置 className 属性:

To replace all existing classes with one or more new classes, set the className attribute:

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

(您可以使用空格分隔的列表来应用多个类.)

(You can use a space-delimited list to apply multiple classes.)

要向元素添加类,而不删除/影响现有值,请附加一个空格和新的类名,如下所示:

To add a class to an element, without removing/affecting existing values, append a space and the new classname, like so:

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

从元素中删除一个类:

要删除元素的单个类,而不影响其他潜在的类,需要一个简单的正则表达式替换:

To remove a class from an element:

To remove a single class to an element, without affecting other potential classes, a simple regex replace is required:

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

对这个正则表达式的解释如下:

An explanation of this regex is as follows:

(?:^|s) # Match the start of the string or any single whitespace character

MyClass  # The literal text for the classname to remove

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

g 标志告诉替换根据需要重复,以防多次添加类名.

The g flag tells the replace to repeat as required, in case the class name has been added multiple times.

上面用于删除类的正则表达式也可以用来检查特定类是否存在:

The same regex used above for removing a class can also be used as a check as to whether a particular class exists:

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


### 将这些操作分配给 onclick 事件:

虽然可以直接在 HTML 事件属性中编写 JavaScript(例如 onclick=this.className+='MyClass'"),这不是推荐的行为.特别是在较大的应用程序中,通过将 HTML 标记与 JavaScript 交互逻辑分离来实现更易于维护的代码.


### 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 JavaScript interaction logic.

实现这一点的第一步是创建一个函数,并在 onclick 属性中调用该函数,例如:

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>

(不需要在脚本标签中包含此代码,这只是为了示例的简洁,将 JavaScript 包含在不同的文件中可能更合适.)

第二步是将 onclick 事件从 HTML 中移到 JavaScript 中,例如使用 addEventListener

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>

(请注意,window.onload 部分是必需的,以便该函数的内容在 HTML 加载完成后 执行 - 如果没有这个,调用 JavaScript 代码时 MyElement 可能不存在,所以该行会失败.)

(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 JavaScript code is called, so that line would fail.)

以上代码全部使用标准 JavaScript,但是,通常的做法是使用框架或库来简化常见任务,并从您在编写您的代码时可能没有想到的修复错误和边缘情况中受益.代码.

The above code is all in standard JavaScript, however, it is common practice 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.

虽然有些人认为添加一个约 50 KB 的框架来简单地更改类是多余的,但如果您正在执行任何大量的 JavaScript 工作或任何可能具有不寻常的跨浏览器行为的工作,则非常值得考虑.

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

(大致来说,库是为特定任务设计的一组工具,而框架通常包含多个库并执行一套完整的职责.)

上面的示例已使用 jQuery 复制如下,这可能是最常用的 JavaScript 库(尽管还有其他值得研究的库)也是).

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

(注意这里的 $ 是 jQuery 对象.)

(Note that $ here is the jQuery object.)

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

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

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

此外,jQuery 提供了一个快捷方式来添加一个不适用的类,或者删除一个适用的类:

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

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


### 使用 jQuery 为单击事件分配一个函数:


### Assigning a function to a click event with jQuery:

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

或者,不需要 ID:

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

这篇关于如何使用 JavaScript 更改元素的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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