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


当前回答

我会使用jQuery编写如下内容:

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

这段代码添加了一个函数,当单击id some元素的元素时调用该函数。如果元素的class属性还不是它的一部分,则该函数会将单击的内容追加到该元素的class特性中,如果它存在,则会将其删除。

是的,您确实需要在页面中添加对jQuery库的引用才能使用这段代码,但至少您可以确信库中的大多数函数都可以在几乎所有现代浏览器上运行,并且这将节省您实现自己代码的时间。

其他回答

我只是想把这个扔进去:

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

此外,您还可以扩展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');
}

这是演示。

这对我很有用:

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

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

可以这样使用node.className:

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

根据PPK,这应该在Internet Explorer 5.5及更高版本中工作。

在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