如何使用JavaScript更改HTML元素的类以响应onclick或任何其他事件?
当前回答
function classed(el, class_name, add_class) {
const re = new RegExp("(?:^|\\s)" + class_name + "(?!\\S)", "g");
if (add_class && !el.className.match(re)) el.className += " " + class_name
else if (!add_class) el.className = el.className.replace(re, '');
}
使用PeterBoughton的答案,这里有一个简单的跨浏览器函数来添加和删除类。
添加类:
classed(document.getElementById("denis"), "active", true)
删除类:
classed(document.getElementById("denis"), "active", false)
其他回答
这对我很有用:
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及更高版本中工作。
我在代码中使用了以下普通JavaScript函数。它们使用正则表达式和indexOf,但不需要在正则表达式中引用特殊字符。
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, "");
}
}
您也可以在现代浏览器中使用element.classList。
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>
下面是一个简单的jQuery代码:
$(".class1").click(function(argument) {
$(".parentclass").removeClass("classtoremove");
setTimeout(function (argument) {
$(".parentclass").addClass("classtoadd");
}, 100);
});
在这里
Class1是事件的侦听器。父类是托管要更改的类的类Classtoremove是您的旧类。要添加的类是要添加的新类。100是类被改变的超时延迟。
推荐文章
- 使伸缩项目正确浮动
- Babel 6改变了它导出默认值的方式
- 如何配置历史记录?
- ES6模板文字可以在运行时被替换(或重用)吗?
- [Vue警告]:找不到元素
- 可以在setInterval()内部调用clearInterval()吗?
- AngularJS控制器的生命周期是什么?
- 无法读取未定义的属性“msie”- jQuery工具
- 形式内联内的形式水平在twitter bootstrap?
- 我的蛋蛋怎么不见了?
- JavaScript中的排列?
- 自定义元素在HTML5中有效吗?
- JavaScript中有睡眠/暂停/等待功能吗?
- 如何触发自动填充在谷歌Chrome?
- 创建圈div比使用图像更容易的方法?