如何使用JavaScript更改HTML元素的类以响应onclick或任何其他事件?
当前回答
可以这样使用node.className:
document.getElementById('foo').className = 'bar';
根据PPK,这应该在Internet Explorer 5.5及更高版本中工作。
其他回答
TL;博士:
document.getElementById('id').className = 'class'
OR
document.getElementById('id').classList.add('class');
document.getElementById('id').classList.remove('class');
就是这样。
而且,如果你真的想知道原因并教育自己,那么我建议阅读彼得·布顿的答案。太完美了。
注:
这可以通过(文档或事件)实现:
按ID获取元素()getElementsByClassName()查询选择器()查询选择器全部()
哇,奇怪这里有这么多过分的答案。。。
<div class="firstClass" onclick="this.className='secondClass'">
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)
我会使用jQuery编写如下内容:
jQuery(function($) {
$("#some-element").click(function() {
$(this).toggleClass("clicked");
});
});
这段代码添加了一个函数,当单击id some元素的元素时调用该函数。如果元素的class属性还不是它的一部分,则该函数会将单击的内容追加到该元素的class特性中,如果它存在,则会将其删除。
是的,您确实需要在页面中添加对jQuery库的引用才能使用这段代码,但至少您可以确信库中的大多数函数都可以在几乎所有现代浏览器上运行,并且这将节省您实现自己代码的时间。
这里有一个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。
也可以在这里看到动态创建新类的答案。
推荐文章
- 使伸缩项目正确浮动
- Babel 6改变了它导出默认值的方式
- 如何配置历史记录?
- ES6模板文字可以在运行时被替换(或重用)吗?
- [Vue警告]:找不到元素
- 可以在setInterval()内部调用clearInterval()吗?
- AngularJS控制器的生命周期是什么?
- 无法读取未定义的属性“msie”- jQuery工具
- 形式内联内的形式水平在twitter bootstrap?
- 我的蛋蛋怎么不见了?
- JavaScript中的排列?
- 自定义元素在HTML5中有效吗?
- JavaScript中有睡眠/暂停/等待功能吗?
- 如何触发自动填充在谷歌Chrome?
- 创建圈div比使用图像更容易的方法?