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


当前回答

是的,有很多方法可以做到这一点。在ES6语法中,我们可以很容易地实现。使用此代码切换添加和删除类。

const tabs=document.querySelectorAll('.menu-li');for(制表符的let制表符){tab.onclick=函数(){let activetab=document.querySelectorAll('li.active');activetab[0].classList.remove('active')tab.classList.add('active');}}正文{填充:20px;字体系列:无衬线;}上一页{边距:20px 0;列表样式:无;}李{背景:#dfdfdf;填充:10px;边距:6px 0;光标:指针;}li.活动{背景:#2794c7;字号:粗体;颜色:#ffffff;}<i> 请单击项目:</i><ul class=“menu”><li class=“active”><span>三个</span></li><li>两个</span></li><li>一个</span></li></ul>

其他回答

classList DOM API:

添加和删除类的一种非常方便的方式是classListDOMAPI。该API允许我们选择特定DOM元素的所有类,以便使用JavaScript修改列表。例如:

const el=document.getElementById(“main”);console.log(el.classList);<div class=“content wrapper animated”id=“main”></div>

我们可以在日志中观察到,我们正在取回一个对象,它不仅包含元素的类,还包含许多辅助方法和财产。此对象继承自接口DOMTokenList,该接口在DOM中用于表示一组空格分隔的令牌(如类)。

例子:

const el=document.getElementById('container');函数addClass(){el.classList.add('newclass');}函数replaceClass(){el.classList.replace('fo','newFoo');}函数removeClass(){el.classList.remove('bar');}按钮{边距:20px;}.foo文件{颜色:红色;}.newFoo{颜色:蓝色;}.巴{背景色:粉蓝色;}.new类{边框:2px实心绿色;}<div class=“foo bar”id=“container”>“全身出汗”在natus error sit volupatim accusantium doloremque audantium,totam rem开胃酒,eaque ipsa quae ab illo inventore veritatis et准建筑风格的生活格言不明确。Nemo enim ipsam公司卷舌</div><button onclick=“addClass()”>addClass</button><button onclick=“replaceClass()”>replaceClass</button><button onclick=“removeClass()”>removeClass</button>

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

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

参见JSFiddle。

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

Try:

element.className='second'

函数更改(box){box.className='second'}.first{width:70px;height:70px,background:#ff0}.second{width:150px;height:150px,background:#f00;transition:1s}<div onclick=“change(this)”class=“first”>单击我</div>

这对我很有用:

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

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

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

这是演示。