如何使用JavaScript更改HTML元素的类以响应onclick或任何其他事件?
当前回答
使用纯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);
}
}
其他回答
此外,您还可以扩展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');
}
这是演示。
我会使用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(' ');
}
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>
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方法。
推荐文章
- 使伸缩项目正确浮动
- Babel 6改变了它导出默认值的方式
- 如何配置历史记录?
- ES6模板文字可以在运行时被替换(或重用)吗?
- [Vue警告]:找不到元素
- 可以在setInterval()内部调用clearInterval()吗?
- AngularJS控制器的生命周期是什么?
- 无法读取未定义的属性“msie”- jQuery工具
- 形式内联内的形式水平在twitter bootstrap?
- 我的蛋蛋怎么不见了?
- JavaScript中的排列?
- 自定义元素在HTML5中有效吗?
- JavaScript中有睡眠/暂停/等待功能吗?
- 如何触发自动填充在谷歌Chrome?
- 创建圈div比使用图像更容易的方法?