本文摘自PHP中文网,作者青灯夜游,侵删。
js修改css类的方法:1、使用className属性,语法“元素对象.className="css类名"”;2、使用setAttribute()方法,语法“元素对象.setAttribute("class", "css类名")”。

本教程操作环境:windows7系统、javascript1.8.5版、Dell G3电脑。
方法1:使用className属性
className 属性设置或返回元素的 class 属性。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | <!DOCTYPE html>
< html >
< head >
< meta charset = "utf-8" >
< style type = "text/css" >
.mystyle{
background-color: palegoldenrod;
}
.otherstyle{
background-color: palevioletred;
}
</ style >
</ head >
< body id = "myid" class = "mystyle" >
< input type = "button" value = "更改类名" onclick = "changeClass()" />< br />< br />
< div id = "div" >Body CSS class名为:mystyle</ div >
< script >
function changeClass(){
var x=document.getElementById('myid');
x.className="otherstyle";
document.getElementById('div').innerHTML="Body CSS class名为:"+ x.className;
}
</ script >
</ body >
</ html >
|
效果图:

方法2:使用setAttribute() 方法
setAttribute() 方法添加指定的属性,并为其赋指定的值。
如果这个指定的属性已存在,则仅设置/更改值。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | <!DOCTYPE html>
< html >
< head >
< meta charset = "utf-8" >
< style type = "text/css" >
.mystyle{
background-color: palegoldenrod;
}
.otherstyle{
background-color: palevioletred;
}
</ style >
</ head >
< body id = "myid" class = "mystyle" >
< input type = "button" value = "更改类名" onclick = "changeClass()" />< br />< br />
< div id = "div" >Body CSS class名为:mystyle</ div >
< script >
function changeClass(){
var x=document.getElementById('myid');
x.setAttribute("class", "otherstyle");
document.getElementById('div').innerHTML="Body CSS class名为:"+ x.className;
}
</ script >
</ body >
</ html >
|
效果图:

【相关推荐:javascript学习教程】
以上就是js怎么修改css类的详细内容,更多文章请关注木庄网络博客!
相关阅读 >>
jquery中text(),html()和val()之间有何区别?
浅谈javascript执行机制
8个编写优秀js代码的技巧和窍门(分享)
javascript和sql有什么区别
javascript简称什么
ie浏览器不支持javascript怎么办
js怎么替换字符串?
canvas的手绘风格图形库rough.js
javascript怎么判断是否为整数
javascript就是es5吗
更多相关阅读请进入《javascript》频道 >>
人民邮电出版社
本书对 Vue.js 3 技术细节的分析非常可靠,对于需要深入理解 Vue.js 3 的用户会有很大的帮助。——尤雨溪,Vue.js作者
转载请注明出处:木庄网络博客 » js怎么修改css类