如何使用JavaScript更改HTML元素的类以响应onclick或任何其他事件?
当前回答
可以这样使用node.className:
document.getElementById('foo').className = 'bar';
根据PPK,这应该在Internet Explorer 5.5及更高版本中工作。
其他回答
你也可以这样做:
document.getElementById('id').classList.add('class');
document.getElementById('id').classList.remove('class');
要切换类(如果存在则删除,否则添加):
document.getElementById('id').classList.toggle('class');
对于jQuery这样的库,这是最简单的:
<input type="button" onClick="javascript:test_byid();" value="id='second'" />
<script>
function test_byid()
{
$("#second").toggleClass("highlight");
}
</script>
无意冒犯,但动态更改类是不清楚的,因为它迫使CSS解释器重新计算整个网页的视觉呈现。
原因是CSS解释器几乎不可能知道是否可以更改任何继承或级联,因此简单的答案是:
永远不要动态更改className!-)
但通常只需要更改一两个属性,这很容易实现:
function highlight(elm){
elm.style.backgroundColor ="#345";
elm.style.color = "#fff";
}
可以这样使用node.className:
document.getElementById('foo').className = 'bar';
根据PPK,这应该在Internet Explorer 5.5及更高版本中工作。
哇,奇怪这里有这么多过分的答案。。。
<div class="firstClass" onclick="this.className='secondClass'">
推荐文章
- 使伸缩项目正确浮动
- Babel 6改变了它导出默认值的方式
- 如何配置历史记录?
- ES6模板文字可以在运行时被替换(或重用)吗?
- [Vue警告]:找不到元素
- 可以在setInterval()内部调用clearInterval()吗?
- AngularJS控制器的生命周期是什么?
- 无法读取未定义的属性“msie”- jQuery工具
- 形式内联内的形式水平在twitter bootstrap?
- 我的蛋蛋怎么不见了?
- JavaScript中的排列?
- 自定义元素在HTML5中有效吗?
- JavaScript中有睡眠/暂停/等待功能吗?
- 如何触发自动填充在谷歌Chrome?
- 创建圈div比使用图像更容易的方法?