如何使用JavaScript更改HTML元素的类以响应onclick或任何其他事件?
当前回答
哇,奇怪这里有这么多过分的答案。。。
<div class="firstClass" onclick="this.className='secondClass'">
其他回答
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>
无意冒犯,但动态更改类是不清楚的,因为它迫使CSS解释器重新计算整个网页的视觉呈现。
原因是CSS解释器几乎不可能知道是否可以更改任何继承或级联,因此简单的答案是:
永远不要动态更改className!-)
但通常只需要更改一两个属性,这很容易实现:
function highlight(elm){
elm.style.backgroundColor ="#345";
elm.style.color = "#fff";
}
对于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);
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这样的库,这是最简单的:
<input type="button" onClick="javascript:test_byid();" value="id='second'" />
<script>
function test_byid()
{
$("#second").toggleClass("highlight");
}
</script>
推荐文章
- 如何将“camelCase”转换为“Camel Case”?
- 我们可以在另一个JS文件中调用用一个JavaScript编写的函数吗?
- 如何使用JavaScript重新加载ReCaptcha ?
- 设置TextView文本从html格式的字符串资源在XML
- jQuery。由于转义了JSON中的单引号,parseJSON抛出“无效JSON”错误
- 在JavaScript关联数组中动态创建键
- ReactJS和公共文件夹中的图像
- 在React Native中使用Fetch授权头
- 为什么我的球(物体)没有缩小/消失?
- Twitter Bootstrap 3 Sticky Footer
- 如何使用jQuery检测页面的滚动位置
- if(key in object)或者if(object. hasownproperty (key)
- 一元加/数字(x)和parseFloat(x)之间的区别是什么?
- angularjs中的compile函数和link函数有什么区别
- 删除绑定中添加的事件监听器