如何使用JavaScript更改HTML元素的类以响应onclick或任何其他事件?
当前回答
JavaScript中有一个属性className,用于更改HTML元素类的名称。现有的类值将替换为您在className中分配的新类值。
<!DOCTYPE html>
<html>
<head>
<title>How can I change the class of an HTML element in JavaScript?</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
<h1 align="center"><i class="fa fa-home" id="icon"></i></h1><br />
<center><button id="change-class">Change Class</button></center>
<script>
var change_class = document.getElementById("change-class");
change_class.onclick = function()
{
var icon=document.getElementById("icon");
icon.className = "fa fa-gear";
}
</script>
</body>
</html>
Credit-如何在JavaScript中更改HTML元素的类名
其他回答
此外,您还可以扩展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');
}
这是演示。
选项。
这里有一个小样式与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")
好的,我认为在这种情况下,您应该使用jQuery或用纯JavaScript编写自己的方法。我的首选是添加我自己的方法,而不是将所有jQuery注入到我的应用程序中,如果我出于其他原因不需要的话。
我想在我的JavaScript框架中添加一些处理添加类、删除类等的功能。类似于jQuery,IE9+完全支持这一点。另外,我的代码是用ES6编写的,所以您需要确保浏览器支持它,或者使用类似Babel的语言,否则需要在代码中使用ES5语法。同样通过这种方式,我们通过ID查找元素,这意味着元素需要有一个要选择的ID:
// Simple JavaScript utilities for class management in ES6
var classUtil = {
addClass: (id, cl) => {
document.getElementById(id).classList.add(cl);
},
removeClass: (id, cl) => {
document.getElementById(id).classList.remove(cl);
},
hasClass: (id, cl) => {
return document.getElementById(id).classList.contains(cl);
},
toggleClass: (id, cl) => {
document.getElementById(id).classList.toggle(cl);
}
}
您可以简单地使用它们,如下所示。假设元素的id为“id”,类为“class”。确保将它们作为字符串传递。您可以按如下方式使用该实用程序:
classUtil.addClass('myId', 'myClass');
classUtil.removeClass('myId', 'myClass');
classUtil.hasClass('myId', 'myClass');
classUtil.toggleClass('myId', 'myClass');
JavaScript中有一个属性className,用于更改HTML元素类的名称。现有的类值将替换为您在className中分配的新类值。
<!DOCTYPE html>
<html>
<head>
<title>How can I change the class of an HTML element in JavaScript?</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
<h1 align="center"><i class="fa fa-home" id="icon"></i></h1><br />
<center><button id="change-class">Change Class</button></center>
<script>
var change_class = document.getElementById("change-class");
change_class.onclick = function()
{
var icon=document.getElementById("icon");
icon.className = "fa fa-gear";
}
</script>
</body>
</html>
Credit-如何在JavaScript中更改HTML元素的类名
在我的一个不使用jQuery的旧项目中,我构建了以下函数,用于添加、删除和检查元素是否具有类:
function hasClass(ele, cls) {
return ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
}
function addClass(ele, cls) {
if (!hasClass(ele, cls))
ele.className += " " + cls;
}
function removeClass(ele, cls) {
if (hasClass(ele, cls)) {
var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
ele.className = ele.className.replace(reg, ' ');
}
}
因此,例如,如果我想onclick向按钮添加一些类,我可以使用这个:
<script type="text/javascript">
function changeClass(btn, cls) {
if(!hasClass(btn, cls)) {
addClass(btn, cls);
}
}
</script>
...
<button onclick="changeClass(this, "someClass")">My Button</button>
现在可以肯定,使用jQuery会更好。
推荐文章
- 使伸缩项目正确浮动
- Babel 6改变了它导出默认值的方式
- 如何配置历史记录?
- ES6模板文字可以在运行时被替换(或重用)吗?
- [Vue警告]:找不到元素
- 可以在setInterval()内部调用clearInterval()吗?
- AngularJS控制器的生命周期是什么?
- 无法读取未定义的属性“msie”- jQuery工具
- 形式内联内的形式水平在twitter bootstrap?
- 我的蛋蛋怎么不见了?
- JavaScript中的排列?
- 自定义元素在HTML5中有效吗?
- JavaScript中有睡眠/暂停/等待功能吗?
- 如何触发自动填充在谷歌Chrome?
- 创建圈div比使用图像更容易的方法?