js怎么通过类来修改css样式
时间:2022-02-11 16:05
在JavaScript中,可以利用setAttribute()方法来通过类修改css样式,只需要修改指定元素的“class”属性值即可,语法“元素对象.setAttribute("class", "新类名");”。 本教程操作环境:windows7系统、javascript1.8.5版、Dell G3电脑。 在JavaScript中,可以利用setAttribute()方法来通过类修改css样式。 下面通过代码示例来具体看看: 效果图: 说明: setAttribute() 方法添加指定的属性,并为其赋指定的值。 如果这个指定的属性已存在,则仅设置/更改值。 语法 (学习视频分享:css视频教程) 以上就是js怎么通过类来修改css样式的详细内容,更多请关注gxlsystem.com其它相关文章!<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<style>
.style1{
height: 50px;
border: 1px solid red;
}
.style2{
border: 3px dashed #AFEEEE;
padding: 10px;
}
</style>
</head>
<body>
<div id="style" class="style1">测试文本</div><br />
<input type="button" value="更改类名" onclick="changeStyle()" />
</body>
<script>
function changeStyle() {
var obj = document.getElementById("style");
obj.setAttribute("class", "style2");
}
</script>
</html>
element.setAttribute(attributename,attributevalue)
参数 类型 描述 attributename String 必需。您希望添加的属性的名称。 attributevalue String 必需。您希望添加的属性值。