使用JavaScript更改元素的类 [英] Change an element's class with JavaScript

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

问题描述


如何使用JavaScript更改一个HTML元素类以响应 onClick 事件? >解决方案

现代HTML5技术用于更改课程



现代浏览器添加了 classList ,它提供了方便操作类而不需要库的方法:

  document.getElementById(MyElement)。classList.add('MyClass'); 

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

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

document.getElementById(MyElement)。classList.toggle('我的课');

不幸的是,这些在v10之前的Internet Explorer中不起作用,尽管有一个 shim 为IE8和IE9添加支持,可从此页面。但是,越来越多的支持



简单的跨浏览器解决方案



选择元素的标准JavaScript方式是使用 document.getElementById(Id) ,这是以下示例使用的 - 你可以以其他方式获得元素,而在正确的情况下可以简单地使用这个,但是详细的说明超出了答案的范围。



要更改元素的所有类:



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

  document.getElementById(MyElement)。className =MyClass; 

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



要向元素添加一个额外的类:



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

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



从元素中删除一个类:



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

 文档。 getElementById(MyElement)。className = 
document.getElementById(MyElement)。className.replace
(/(?:^ | \s)MyClass(?!\S)/ g ,'')
/ *代码包装可读性 - 以上是所有一个语句* /

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

 (?:^ | \s)#匹配字符串的开头,或任何单个空格字符

MyClass#删除

(?!\S)的类名的文字文本#验证上述的负面前瞻是整个类名
#确保
#之后没有非空格字符(即必须是字符串或空格的结尾)

g 标志te为了检查一个类是否已经应用于一个元素:





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

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




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



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



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

 < script type =text / javascript> 
function changeClass()
{
//上面的代码示例
}
< / script>
...
< button onclick =changeClass()>我的按钮< / button>

(脚本标签中不需要这个代码,这是简单的简单的例子,并将JavaScript包含在不同的文件中可能更合适。)



第二步是移动例如,使用 addEventListener

 < script type =text / javascript> 
function changeClass()
{
//上面的代码示例
}

window.onload = function()
{
document.getElementById(MyElement)。addEventListener('click',changeClass);
}
< / script>
...
< button id =MyElement>我的按钮< / button>

(请注意,window.onload部分是必需的,以便执行该功能的内容之后,HTML已经完成加载 - 没有这个,当调用JavaScript代码时,MyElement可能不存在,因此该行将失败。)






JavaScript框架和库



上面的代码都是标准的JavaScript,练习使用框架或库来简化常见任务,以及在编写代码时可能无法想到的修复错误和边缘案例。



虽然有些人认为增加一个约50 KB的框架来简单地改变一个类,如果你正在进行大量的JavaScript工作,或任何可能有异常跨浏览器行为的东西,这是非常值得考虑的。 p>

(很大程度上,一个库是一组专为特定任务而设计的工具,作业通常包含多个库并执行完整的任务。)



上面的示例已使用 jQuery ,可能是最常用的JavaScript库(尽管还有其他的值得调查)。





使用jQuery更改类:



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

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

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

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

  $( '#MyElement')toggleClass( 'MyClass的')。 




分配对jQuery的点击事件的功能:



  $('#MyElement')点击(changeClass); 

或不需要id:

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



How can I change a class of an HTML element in response to an onClick event using JavaScript?

解决方案

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');

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.

Simple cross-browser solution

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.

To change all classes for an element:

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 an additional class to an element:

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 end of string or a space)

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

To check if a class is already applied to an element:

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)/) )


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.

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 JavaScript 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 JavaScript code 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 ~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 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);


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

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