如何使用JavaScript更改HTML元素的类以响应onclick或任何其他事件?
当前回答
哇,奇怪这里有这么多过分的答案。。。
<div class="firstClass" onclick="this.className='secondClass'">
其他回答
下面是一个简单的jQuery代码:
$(".class1").click(function(argument) {
$(".parentclass").removeClass("classtoremove");
setTimeout(function (argument) {
$(".parentclass").addClass("classtoadd");
}, 100);
});
在这里
Class1是事件的侦听器。父类是托管要更改的类的类Classtoremove是您的旧类。要添加的类是要添加的新类。100是类被改变的超时延迟。
对于jQuery这样的库,这是最简单的:
<input type="button" onClick="javascript:test_byid();" value="id='second'" />
<script>
function test_byid()
{
$("#second").toggleClass("highlight");
}
</script>
此外,您还可以扩展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');
}
这是演示。
为了补充来自另一个流行框架Google Closures的信息,请查看他们的dom/classes类:
goog.dom.classes.add(element, var_args)
goog.dom.classes.addRemove(element, classesToRemove, classesToAdd)
goog.dom.classes.remove(element, var_args)
选择元素的一个选项是使用goog.dom.query和CSS 3选择器:
var myElement = goog.dom.query("#MyElement")[0];
对于IE v6-9(其中不支持classList,并且不希望使用polyfills):
var elem = document.getElementById('some-id');
// don't forget the extra space before the class name
var classList = elem.getAttribute('class') + ' other-class-name';
elem.setAttribute('class', classList);
推荐文章
- 使伸缩项目正确浮动
- Babel 6改变了它导出默认值的方式
- 如何配置历史记录?
- ES6模板文字可以在运行时被替换(或重用)吗?
- [Vue警告]:找不到元素
- 可以在setInterval()内部调用clearInterval()吗?
- AngularJS控制器的生命周期是什么?
- 无法读取未定义的属性“msie”- jQuery工具
- 形式内联内的形式水平在twitter bootstrap?
- 我的蛋蛋怎么不见了?
- JavaScript中的排列?
- 自定义元素在HTML5中有效吗?
- JavaScript中有睡眠/暂停/等待功能吗?
- 如何触发自动填充在谷歌Chrome?
- 创建圈div比使用图像更容易的方法?