如何使用JavaScript更改HTML元素的类以响应onclick或任何其他事件?
当前回答
classList DOM API:
添加和删除类的一种非常方便的方式是classListDOMAPI。该API允许我们选择特定DOM元素的所有类,以便使用JavaScript修改列表。例如:
const el=document.getElementById(“main”);console.log(el.classList);<div class=“content wrapper animated”id=“main”></div>
我们可以在日志中观察到,我们正在取回一个对象,它不仅包含元素的类,还包含许多辅助方法和财产。此对象继承自接口DOMTokenList,该接口在DOM中用于表示一组空格分隔的令牌(如类)。
例子:
const el=document.getElementById('container');函数addClass(){el.classList.add('newclass');}函数replaceClass(){el.classList.replace('fo','newFoo');}函数removeClass(){el.classList.remove('bar');}按钮{边距:20px;}.foo文件{颜色:红色;}.newFoo{颜色:蓝色;}.巴{背景色:粉蓝色;}.new类{边框:2px实心绿色;}<div class=“foo bar”id=“container”>“全身出汗”在natus error sit volupatim accusantium doloremque audantium,totam rem开胃酒,eaque ipsa quae ab illo inventore veritatis et准建筑风格的生活格言不明确。Nemo enim ipsam公司卷舌</div><button onclick=“addClass()”>addClass</button><button onclick=“replaceClass()”>replaceClass</button><button onclick=“removeClass()”>removeClass</button>
其他回答
线路
document.getElementById("MyElement").className = document.getElementById("MyElement").className.replace(/\bMyClass\b/','')
应该是:
document.getElementById("MyElement").className = document.getElementById("MyElement").className.replace('/\bMyClass\b/','');
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)
你也可以这样做:
document.getElementById('id').classList.add('class');
document.getElementById('id').classList.remove('class');
要切换类(如果存在则删除,否则添加):
document.getElementById('id').classList.toggle('class');
可以这样使用node.className:
document.getElementById('foo').className = 'bar';
根据PPK,这应该在Internet Explorer 5.5及更高版本中工作。
无意冒犯,但动态更改类是不清楚的,因为它迫使CSS解释器重新计算整个网页的视觉呈现。
原因是CSS解释器几乎不可能知道是否可以更改任何继承或级联,因此简单的答案是:
永远不要动态更改className!-)
但通常只需要更改一两个属性,这很容易实现:
function highlight(elm){
elm.style.backgroundColor ="#345";
elm.style.color = "#fff";
}
推荐文章
- 我如何使用Jest模拟JavaScript的“窗口”对象?
- 如何使Bootstrap 4卡在卡列相同的高度?
- 我如何等待一个承诺完成之前返回一个函数的变量?
- 在JavaScript中根据键值查找和删除数组中的对象
- 使嵌套JavaScript对象平放/不平放的最快方法
- 使用域集图例引导
- 如何以及为什么'a'['toUpperCase']()在JavaScript工作?
- 音频停止功能
- 有Grunt生成index.html不同的设置
- 如何禁用谷歌翻译从HTML在Chrome
- 文档之间的区别。addEventListener和window。addEventListener?
- 如何检查动态附加的事件监听器是否存在?
- 如何写setTimeout与参数Coffeescript
- 将JavaScript字符串中的多个空格替换为单个空格
- 向HTML表中添加水平滚动条