如何使用JavaScript更改HTML元素的类以响应onclick或任何其他事件?
当前回答
这对我很有用:
function setCSS(eleID) {
var currTabElem = document.getElementById(eleID);
currTabElem.setAttribute("class", "some_class_name");
currTabElem.setAttribute("className", "some_class_name");
}
其他回答
选项。
这里有一个小样式与classList的示例,让您了解您有哪些可用选项,以及如何使用classList完成您想要的操作。
样式与类别列表
style和classList之间的区别在于,使用style可以将其添加到元素的样式财产中,但classList有点控制元素的类(add、remove、toggle、contain),我将向您展示如何使用add和remove方法,因为它们是最流行的方法。
样式示例
如果要将margin-top属性添加到元素中,可以这样做:
// Get the Element
const el = document.querySelector('#element');
// Add CSS property
el.style.margintop = "0px"
el.style.margintop = "25px" // This would add a 25px to the top of the element.
classList示例
假设我们有一个<div class=“class-a class-b”>,在本例中,我们已经向div元素添加了两个类,class-a和class-b,我们希望控制删除哪些类和添加哪些类。这就是classList变得方便的地方。
删除类-b
// Get the Element
const el = document.querySelector('#element');
// Remove class-b style from the element
el.classList.remove("class-b")
添加类-c
// Get the Element
const el = document.querySelector('#element');
// Add class-b style from the element
el.classList.add("class-c")
这是我的版本,完全可用:
function addHTMLClass(item, classname) {
var obj = item
if (typeof item=="string") {
obj = document.getElementById(item)
}
obj.className += " " + classname
}
function removeHTMLClass(item, classname) {
var obj = item
if (typeof item=="string") {
obj = document.getElementById(item)
}
var classes = ""+obj.className
while (classes.indexOf(classname)>-1) {
classes = classes.replace (classname, "")
}
obj.className = classes
}
用法:
<tr onmouseover='addHTMLClass(this,"clsSelected")'
onmouseout='removeHTMLClass(this,"clsSelected")' >
此外,您还可以扩展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');
}
这是演示。
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>
这里有一个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。
也可以在这里看到动态创建新类的答案。
推荐文章
- 我如何使用Jest模拟JavaScript的“窗口”对象?
- 如何使Bootstrap 4卡在卡列相同的高度?
- 我如何等待一个承诺完成之前返回一个函数的变量?
- 在JavaScript中根据键值查找和删除数组中的对象
- 使嵌套JavaScript对象平放/不平放的最快方法
- 使用域集图例引导
- 如何以及为什么'a'['toUpperCase']()在JavaScript工作?
- 音频停止功能
- 有Grunt生成index.html不同的设置
- 如何禁用谷歌翻译从HTML在Chrome
- 文档之间的区别。addEventListener和window。addEventListener?
- 如何检查动态附加的事件监听器是否存在?
- 如何写setTimeout与参数Coffeescript
- 将JavaScript字符串中的多个空格替换为单个空格
- 向HTML表中添加水平滚动条