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


当前回答

OP的问题是如何使用JavaScript更改元素的类?

现代浏览器允许您使用一行JavaScript实现这一点:

document.getElementById('id').classList.replace('span1','span2')

classList属性提供了具有多种方法的DOMTokenList。可以使用add()、remove()或replace()等简单操作对元素的classList进行操作。或者像使用key()、values()和entries()来处理对象或Map那样使用非常复杂的类。

彼得·布顿(Peter Boughton)的回答很好,但现在已经超过十年了。所有现代浏览器现在都支持DOMTokenList-请参阅https://caniuse.com/#search=classList甚至Internet Explorer 11也支持一些DOMTokenList方法。

其他回答

下面是一个简单的jQuery代码:

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

在这里

Class1是事件的侦听器。父类是托管要更改的类的类Classtoremove是您的旧类。要添加的类是要添加的新类。100是类被改变的超时延迟。

此外,您还可以扩展HTMLElement对象,以便添加添加、删除、切换和检查类的方法(要点):

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

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

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

这是演示。

线路

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

应该是:

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

在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

你也可以这样做:

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

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

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