使用JavaScript修改元素的类

[英]Change an element's class with JavaScript


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

如何使用JavaScript更改HTML元素的类以响应onClick事件?

30 个解决方案

#1


3235  

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:

现代浏览器已经增加了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('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.

不幸的是,在v10之前,这些都不能在Internet Explorer中工作,但是有一个shim可以为IE8和IE9添加支持,可以从这个页面获得。然而,它得到越来越多的支持。

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.

选择一个元素的标准JavaScript方法是使用. getelementbyid(" Id "),这就是下面的例子使用——你当然可以获得元素在其他方面,在正确的情况下可能仅仅使用这个相反,然而,进入细节这是超出了答案的范围。

To change all classes for an element:

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

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

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:

要将单个类删除到元素中,而不影响其他潜在类,需要简单地替换regex:

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:

对此regex的解释如下:

(?:^|\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.

g标志告诉replace按需重复,以防类名被多次添加。

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:

上面用于删除类的regex也可以用于检查某个特定类是否存在:

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.

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

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

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

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

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

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

第二步是将onclick事件从HTML移动到JavaScript,例如使用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.)

(注意,窗外。需要onload部分,以便在HTML完成加载后执行该函数的内容——如果没有onload部分,在调用JavaScript代码时MyElement可能不存在,因此这一行将失败)。


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.

上面的代码都是标准的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 behaviour, it is well worth considering.

虽然有些人认为添加一个大约50kb的框架来简单地更改类是过犹不及的,但是如果您正在做大量的JavaScript工作,或者任何可能具有异常跨浏览器行为的东西,那么它是值得考虑的。

(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).

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

(Note that $ here is the jQuery object.)

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

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:

此外,jQuery还提供了添加不适用类的快捷方式,或者删除具有以下功能的类:

$('#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);


#2


377  

You could also just do:

你也可以这样做:

document.getElementById('id').classList.add('class');
document.getElementById('id').classList.remove('class');

And to toggle a class (remove if exists else add it):

并切换类(如果存在则删除,添加):

document.getElementById('id').classList.toggle('class');

#3


96  

In one of my old projects that did not use jQuery, I built the following functions for adding, removing, and checking if element has class:

在我以前的一个不使用jQuery的项目中,我构建了以下函数,用于添加、删除和检查元素是否有类:

function hasClass(ele, cls) {
    return ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
}
function addClass(ele, cls) {
    if (!hasClass(ele, cls)) ele.className += " " + cls;
}
function removeClass(ele, cls) {
    if (hasClass(ele, cls)) {
        var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
        ele.className = ele.className.replace(reg, ' ');
    }
}

So, for example, if I want onclick to add some class the the button I can use this:

例如,如果我想要onclick添加一些类按钮,我可以用这个:

<script type="text/javascript">
    function changeClass(btn, cls) {
        if(!hasClass(btn, cls)) {
            addClass(btn, cls);
        }
    }
</script>
...
<button onclick="changeClass(this, "someClass")">My Button</button>

By now for sure it would just better to use jQuery.

现在可以肯定的是,最好使用jQuery。

#4


62  

You can use node.className like so:

您可以使用节点。名称如下:

document.getElementById('foo').className = 'bar';

This should work in IE5.5 and up according to PPK.

这应该在IE5.5中工作,并根据PPK。

#5


45  

Wow, surprised there are so many overkill answers here...

哇,奇怪的是这里有这么多多余的答案……

<div class="firstClass" onclick="this.className='secondClass'">

#6


39  

Using pure JavaScript code:

使用纯JavaScript代码:

function hasClass(ele, cls) {
    return ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
}

function addClass(ele, cls) {
    if (!this.hasClass(ele, cls)) ele.className += " " + cls;
}

function removeClass(ele, cls) {
    if (hasClass(ele, cls)) {
        var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
        ele.className = ele.className.replace(reg, ' ');
    }
}

function replaceClass(ele, oldClass, newClass){
    if(hasClass(ele, oldClass)){
        removeClass(ele, oldClass);
        addClass(ele, newClass);
    }
    return;
}

function toggleClass(ele, cls1, cls2){
    if(hasClass(ele, cls1)){
        replaceClass(ele, cls1, cls2);
    }else if(hasClass(ele, cls2)){
        replaceClass(ele, cls2, cls1);
    }else{
        addClass(ele, cls1);
    }
}

#7


26  

This is working for me:

这对我很有效:

function setCSS(eleID) {
    var currTabElem = document.getElementById(eleID);

    currTabElem.setAttribute("class", "some_class_name");
    currTabElem.setAttribute("className", "some_class_name");
}

#8


15  

As well you could extend HTMLElement object, in order to add methods to add, remove, toggle and check classes (gist):

也可以扩展HTMLElement对象,以便添加添加添加、删除、切换和检查类的方法(gist):

HTMLElement = typeof(HTMLElement) != 'undefiend' ? HTMLElement : Element;

HTMLElement.prototype.addClass = function(string) {
  if (!(string instanceof Array)) {
    string = string.split(' ');
  }
  for(var i = 0, len = string.length; i < len; ++i) {
    if (string[i] && !new RegExp('(\\s+|^)' + string[i] + '(\\s+|$)').test(this.className)) {
      this.className = this.className.trim() + ' ' + string[i];
    }
  }
}

HTMLElement.prototype.removeClass = function(string) {
  if (!(string instanceof Array)) {
    string = string.split(' ');
  }
  for(var i = 0, len = string.length; i < len; ++i) {
    this.className = this.className.replace(new RegExp('(\\s+|^)' + string[i] + '(\\s+|$)'), ' ').trim();
  }
}

HTMLElement.prototype.toggleClass = function(string) {
  if (string) {
    if (new RegExp('(\\s+|^)' + string + '(\\s+|$)').test(this.className)) {
      this.className = this.className.replace(new RegExp('(\\s+|^)' + string + '(\\s+|$)'), ' ').trim();
    } else {
      this.className = this.className.trim() + ' ' + string;
    }
  }
}

HTMLElement.prototype.hasClass = function(string) {
  return string && new RegExp('(\\s+|^)' + string + '(\\s+|$)').test(this.className);
}

And then just use like this (on click will add or remove class):

然后像这样使用(点击将添加或删除类):

document.getElementById('yourElementId').onclick = function() {
  this.toggleClass('active');
}

Here is demo.

这是演示。

#9


14  

Just to add on information from another popular framework, Google Closures, see their dom/classes class:

只需添加来自另一个流行框架谷歌闭包的信息,请参见它们的dom/class类:

goog.dom.classes.add(element, var_args)

goog.dom.classes.addRemove(element, classesToRemove, classesToAdd)

goog.dom.classes.remove(element, var_args)

One option for selecting the element is using goog.dom.query with a CSS3 selector:

选择元素的一个选项是使用google .dom。使用CSS3选择器查询:

var myElement = goog.dom.query("#MyElement")[0];

#10


12  

A couple of minor notes and tweaks on the previous regexes:

对以前的regexes的一些小注释和调整:

You'll want to do it globally in case the class list has the class name more than once. And, you'll probably want to strip spaces from the ends of the class list and convert multiple spaces to one space to keep from getting runs of spaces. None of these things should be a problem if the only code dinking with the class names uses the regex below and removes a name before adding it. But. Well, who knows who might be dinking with the class name list.

如果类列表有不止一次的类名,那么您将希望在全局上执行它。而且,您可能希望从类列表的末尾删除空格,并将多个空格转换为一个空格,以避免获得空格的运行。如果只有使用类名的代码使用下面的regex并在添加名称之前删除名称,那么这些事情都不应该成为问题。但是。谁知道谁在用类名列表吃饭。

This regex is case insensitive so that bugs in class names may show up before the code is used on a browser that doesn't care about case in class names.

这个regex是不区分大小写的,因此类名中的错误可能会在不关心类名大小写的浏览器上使用代码之前出现。

var s = "testing   one   four  one  two";
var cls = "one";
var rg          = new RegExp("(^|\\s+)" + cls + "(\\s+|$)", 'ig');
alert("[" + s.replace(rg, ' ') + "]");
var cls = "test";
var rg          = new RegExp("(^|\\s+)" + cls + "(\\s+|$)", 'ig');
alert("[" + s.replace(rg, ' ') + "]");
var cls = "testing";
var rg          = new RegExp("(^|\\s+)" + cls + "(\\s+|$)", 'ig');
alert("[" + s.replace(rg, ' ') + "]");
var cls = "tWo";
var rg          = new RegExp("(^|\\s+)" + cls + "(\\s+|$)", 'ig');
alert("[" + s.replace(rg, ' ') + "]");

#11


11  

Change an element's CSS class with JavaScript in ASP.NET:

在ASP.NET中使用JavaScript修改元素的CSS类:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    If Not Page.IsPostBack Then
        lbSave.Attributes.Add("onmouseover", "this.className = 'LinkButtonStyle1'")
        lbSave.Attributes.Add("onmouseout", "this.className = 'LinkButtonStyle'")
        lbCancel.Attributes.Add("onmouseover", "this.className = 'LinkButtonStyle1'")
        lbCancel.Attributes.Add("onmouseout", "this.className = 'LinkButtonStyle'")
    End If
End Sub

#12


11  

I would use jQuery and write something like this:

我会用jQuery写这样的东西:

jQuery(function($) {
    $("#some-element").click(function() {
        $(this).toggleClass("clicked");
    });
});

This code adds a function to be called when an element of the id some-element is clicked. The function appends clicked to the element's class attribute if it's not already part of it, and removes it if it's there.

这段代码添加了一个函数,在单击id some-element的元素时调用它。如果元素的class属性不是它的一部分,函数会将其添加到该元素的class属性中,如果元素已经存在,函数会将其删除。

Yes you do need to add a reference to the jQuery library in your page to use this code, but at least you can feel confident the most functions in the library would work on pretty much all the modern browsers, and it will save you time implementing your own code to do the same.

是的,你需要将一个引用添加到jQuery库的页面使用这段代码,但至少你可以自信最功能在图书馆工作几乎所有现代浏览器,它会节省你的时间实现您自己的代码来做同样的事情。

Thanks

谢谢

#13


8  

The line

这条线

document.getElementById("MyElement").className = document.getElementById("MyElement").className.replace(/\bMyClass\b/','')

should be:

应该是:

document.getElementById("MyElement").className = document.getElementById("MyElement").className.replace('/\bMyClass\b/','');

#14


6  

Here's my version, fully working:

这是我的版本,完全工作:

function addHTMLClass(item, classname) {
    var obj = item
    if (typeof item=="string") {
        obj = document.getElementById(item)
    }
    obj.className += " " + classname
}

function removeHTMLClass(item, classname) {
    var obj = item
    if (typeof item=="string") {
        obj = document.getElementById(item)
    }
    var classes = ""+obj.className
    while (classes.indexOf(classname)>-1) {
        classes = classes.replace (classname, "")
    }
    obj.className = classes
}

Usage:

用法:

<tr onmouseover='addHTMLClass(this,"clsSelected")'
onmouseout='removeHTMLClass(this,"clsSelected")' >

#15


5  

Change an element's class in vanilla JavaScript with IE6 support

You may try to use node attributes property to keep compatibility with old browsers even IE6:

您可以尝试使用node属性来保持与旧浏览器的兼容性,甚至IE6:

function getClassNode(element) {
  for (var i = element.attributes.length; i--;)
    if (element.attributes[i].nodeName === 'class')
      return element.attributes[i];
}

function removeClass(classNode, className) {
  var index, classList = classNode.value.split(' ');
  if ((index = classList.indexOf(className)) > -1) {
    classList.splice(index, 1);
    classNode.value = classList.join(' ');
  }
}

function hasClass(classNode, className) {
  return classNode.value.indexOf(className) > -1;
}

function addClass(classNode, className) {
  if (!hasClass(classNode, className))
    classNode.value += ' ' + className;
}

document.getElementById('message').addEventListener('click', function() {
  var classNode = getClassNode(this);
  var className = hasClass(classNode, 'red') && 'blue' || 'red';

  removeClass(classNode, 'red');
  removeClass(classNode, 'blue');

  addClass(classNode, className);
})
.red {
  color: red;
}
.red:before {
  content: 'I am red! ';
}
.red:after {
  content: ' again';
}
.blue {
  color: blue;
}
.blue:before {
  content: 'I am blue! '
}
<span id="message" class="">Click me</span>

#16


5  

Here's a toggleClass to toggle/add/remove a class on an element:

这里有一个切换/添加/删除元素上的类的切换类:

// If newState is provided add/remove theClass accordingly, otherwise toggle theClass
function toggleClass(elem, theClass, newState) {
    var matchRegExp = new RegExp('(?:^|\\s)' + theClass + '(?!\\S)', 'g');
    var add=(arguments.length>2 ? newState : (elem.className.match(matchRegExp) == null));

    elem.className=elem.className.replace(matchRegExp, ''); // clear all
    if (add) elem.className += ' ' + theClass;
}

see jsfiddle

看到jsfiddle

also see my answer here for creating a new class dynamically

在这里还可以看到我动态创建新类的答案

#17


4  

I use the following vanilla JavaScript functions in my code. They use regular expressions and indexOf but do not require quoting special characters in regular expressions.

在我的代码中,我使用了以下的JavaScript函数。它们使用正则表达式和索引,但不需要在正则表达式中引用特殊字符。

function addClass(el, cn) {
    var c0 = (" " + el.className + " ").replace(/\s+/g, " "),
        c1 = (" " + cn + " ").replace(/\s+/g, " ");
    if (c0.indexOf(c1) < 0) {
        el.className = (c0 + c1).replace(/\s+/g, " ").replace(/^ | $/g, "");
    }
}

function delClass(el, cn) {
    var c0 = (" " + el.className + " ").replace(/\s+/g, " "),
        c1 = (" " + cn + " ").replace(/\s+/g, " ");
    if (c0.indexOf(c1) >= 0) {
        el.className = c0.replace(c1, " ").replace(/\s+/g, " ").replace(/^ | $/g, "");
    }
}

You can also use element.classList in modern browsers.

您还可以使用元素。在现代浏览器中班级名册。

#18


3  

It can be done.

这是可以做到的。

HTML:

HTML:

<div class="red" id="text">
<a href="#" onclick="changeClass();">Fahad</a>
</div>

CSS:

CSS:

.red a{
  color:red;
}
.black a{
  color:black;
}

JavaScript:

JavaScript:

function changeClass(){
document.getElementById("text").className = "black";
}

Fiddle.

小提琴。

#19


2  

If you want to remove a class, you can do:

如果你想删除一个类,你可以:

ELEMENT.classList.remove("CLASS_NAME");

To add a class:

添加一个类:

ELEMENT.classList.add('CLASS_NAME');

#20


1  

This is nice one that I found helpful.

这个不错,我觉得很有用。

function classChangeFn() {
        document.getElementById("MyElement").className = "";
    }

window.onload = function(){
        document.getElementById("MyElement").addEventListener( 'click' , classChangeFn );
    }

#21


1  

After a long search i found the best class management solution without the document.getElementById()

经过长时间的搜索,我找到了没有document.getElementById()的最佳类管理解决方案

var els = [].slice.apply(document.getElementsByClassName("no-js"));
for (var i = 0; i < els.length; i++) {
    els[i].className = els[i].className.replace(/ *\bno-js\b/g, "js");
}

The original place of solution: https://stackoverflow.com/a/8708944/1589669

解决方案的原始位置:https://stackoverflow.com/a/8708944/1589669。

#22


1  

From here : https://developer.mozilla.org/en-US/docs/Web/API/Element/classList

在这里:https://developer.mozilla.org/en-US/docs/Web/API/Element/classList

On click action, You can try using:

点击操作,您可以尝试使用:

replace( oldClass, newClass )
Replaces an existing class with a new class.

替换(oldClass, newClass)用一个新类替换现有的类。

Ex:

例:

var myDiv = document.getElementById('myElement'); 
myDiv.classList.contains('myCssClass');
myDiv.classList.replace("myCssClass", "myCssClass_new");

#23


0  

Just thought I'd throw this in:

我只是想说

function inArray(val, ary){
  for(var i=0,l=ary.length; i<l; i++){
    if(ary[i] === val){
      return true;
    }
  }
  return false;
}
function removeClassName(classNameS, fromElement){
  var x = classNameS.split(/\s/), s = fromElement.className.split(/\s/), r = [];
  for(var i=0,l=s.length; i<l; i++){
    if(!iA(s[i], x))r.push(s[i]);
  }
  fromElement.className = r.join(' ');
}
function addClassName(classNameS, toElement){
  var s = toElement.className.split(/\s/);
  s.push(c); toElement.className = s.join(' ');
}

#24


0  

Working JavaScript code:

工作JavaScript代码:

<div id="div_add" class="div_add">Add class from Javascript</div>
<div id="div_replace" class="div_replace">Replace class from Javascript</div>
<div id="div_remove" class="div_remove">Remove class from Javascript</div>
<button onClick="div_add_class();">Add class from Javascript</button>
<button onClick="div_replace_class();">Replace class from Javascript</button>
<button onClick="div_remove_class();">Remove class from Javascript</button>
<script type="text/javascript">
    function div_add_class()
    {
        document.getElementById("div_add").className += " div_added";
    }
    function div_replace_class()
    {
        document.getElementById("div_replace").className = "div_replaced";
    }
    function div_remove_class()
    {
        document.getElementById("div_remove").className = "";
    }
</script>

You can download a working code from this link.

您可以从该链接下载工作代码。

#25


0  

just say myElement.classList="new-class" unless you need to maintain other existing classes in which case you can use the classList.add, .remove methods.

只是说myElement。classList=“新类”,除非您需要维护其他现有类,在这种情况下,您可以使用类列表。添加、.remove方法。

var doc = document;
var divOne = doc.getElementById("one");
var goButton = doc.getElementById("go");

goButton.addEventListener("click", function() {
  divOne.classList="blue";
});
div{
  min-height:48px;
  min-width:48px;
}
.bordered{
  border: 1px solid black;
}
.green{
  background:green;
}
.blue{
  background: blue;
}
<button id="go">Change Class</button>

<div id="one" class="bordered green">

</div>

#26


0  

OK, I think in this case you should use jQuery or write your own Methods in pure javascript, my preference is adding my own methods rather than injecting all jQuery to my application if I don't need that for other reasons.

好的,我认为在这种情况下,您应该使用jQuery或者用纯javascript编写自己的方法,我的偏好是添加我自己的方法,而不是将所有的jQuery注入到我的应用程序中,如果我出于其他原因不需要jQuery的话。

I'd like to do something like below as methods to my javascript framework to add few functionalities which handle adding classes, deleting classes, etc similar to jQuery, this is fully supported in IE9+, also my code is written in ES6, so you need to make sure your browser support it or you using something like babel, otherwise need to use ES5 syntax in your code, also in this way, we finding element via ID, which means the element needs to have an ID to be selected:

我想做一些类似下面的方法来我的javascript框架添加一些功能,处理添加类,删除类,等类似于jQuery,这是完全支持在IE9 +,还我的代码写在ES6,所以你需要确保你的浏览器支持它或者你使用类似的巴别塔,否则需要在您的代码中使用ES5的语法,也用这种方法,我们发现通过ID元素,这意味着元素需要一个ID选择:

//simple javascript utils for class management in ES6
var classUtil = {

  addClass: (id, cl) => {
    document.getElementById(id).classList.add(cl);
  },

  removeClass: (id, cl) => {
    document.getElementById(id).classList.remove(cl);
  },

  hasClass: (id, cl) => {
    return document.getElementById(id).classList.contains(cl);
  },

  toggleClass: (id, cl) => {
    document.getElementById(id).classList.toggle(cl);
  }

}

and you can simply call use them as below, imagine your element has id of 'id' and class of 'class', make sure you pass them as a string, you can use the util as below:

你可以简单地调用如下所示的use它们,假设你的元素有id为'id'和class为'class'的类,确保你将它们作为字符串传递,你可以使用util如下所示:

classUtil.addClass('myId', 'myClass');
classUtil.removeClass('myId', 'myClass');
classUtil.hasClass('myId', 'myClass');
classUtil.toggleClass('myId', 'myClass');

#27


0  

Let us consider button to be the html element. Let class removed to be button1 and the class to be added is button2 and id is button.

让我们将按钮视为html元素。让类被删除为button1,要添加的类为button2, id为button。

function ClassChange () {
var button=document.getElementById("button");
button.setAttribute("class","button2");
}
<button id="button" class="button1" onclick="ClassChange()">

#28


-2  

Here is simple jQuery code to do that.

下面是简单的jQuery代码。

$(".class1").click(function(argument) {
    $(".parentclass").removeClass("classtoremove");
    setTimeout(function (argument) {
        $(".parentclass").addClass("classtoadd");
    }, 100);
});

Here,

在这里,

  • Class1 is a listener for an event.
  • Class1是事件的侦听器。
  • The parent class is the class which hosts the class you want to change
  • 父类是承载要更改的类的类
  • Classtoremove is the old class you have.
  • 经典是你的老门第。
  • Class to add is the new class that you want to add.
  • 类要添加的是您想要添加的新类。
  • 100 is the timeout delay during which the class is changed.
  • 100是类被更改时的超时延迟。

Good Luck.

祝你好运。

#29


-17  

This is easiest with a library like jQuery:

对于jQuery这样的库,这是最简单的:

<input type="button" onClick="javascript:test_byid();" value="id='second'" />

<script>
function test_byid()
{
    $("#second").toggleClass("highlight");
}
</script>

#30


-54  

No offense, but it's unclever to change class on-the-fly as it forces the CSS interpreter to recalculate the visual presentation of the entire web page.

无意冒犯,但是动态更改类是不明智的,因为这会迫使CSS解释器重新计算整个web页面的可视化表示。

The reason is that it is nearly impossible for the CSS interpreter to know if any inheritance or cascading could be changed, so the short answer is:

原因是CSS解释器几乎不可能知道是否可以更改任何继承或级联,所以简短的回答是:

Never ever change className on-the-fly !-)

永远不要即时更改课程名称!

But usually you'll only need to change a property or two, and that is easily implemented:

但通常你只需要更改一两个属性,这很容易实现:

function highlight(elm){
    elm.style.backgroundColor ="#345";
    elm.style.color = "#fff";
}
智能推荐

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.silva-art.net/blog/2008/10/12/24e4c2e918ebbdad8b53ec625dca9fed.html



 
© 2014-2019 ITdaan.com 粤ICP备14056181号  

赞助商广告