方法:1、使用“对象.style.属性名=”值””;2、使用“对象.style.cssText=”属性名:值””;3、使用“对象.setAttribute(“class”,”类名”)”;4、用setAttribute()函数更改css文件。
本教程操作环境:windows7系统、javascript1.8.5版、Dell G3电脑。
javascript修改css样式的方法(四种)
第一种:使用对象.style.属性名=”值”来修改样式表的类名。
例如:
立即学习“前端免费学习笔记(深入)”;
div1.style.width="100px";
登录后复制
第二种:使用对象.style.cssText=”属性名:值”来修改嵌入式的css。
例:
div1.style.cssText="width:100px;height:100px;background: palevioletred;";
登录后复制
第三种:使用对象.setAttribute(“class”,”类名”)来修改样式表的类名。
例如:
立即学习“前端免费学习笔记(深入)”;
div1.setAttribute("class","div2")
登录后复制
第四种:使用setAttribute()函数更改外联的css文件,从而改变元素的css。
例如:
立即学习“前端免费学习笔记(深入)”;
div1.setAttribute("href","css2.css");
登录后复制
html代码:
1234
登录后复制
css1.css文件
@charset "utf-8";#divBtn1,#divBtn2,#divBtn3,#divBtn4{ width:100px; height:100px; margin-bottom: 10px;}#divBtn1{background:yellowgreen;}#divBtn2{background:paleturquoise;}#divBtn3{border:1px solid #ccc}#divBtn4{background:blue;}.div3{width:100px;height:100px;background:blueviolet}
登录后复制
css2.css文件
@charset "utf-8";#divBtn4{background: greenyellow;}#divBtn1,#divBtn2,#divBtn3,#divBtn4{ width:200px; height:200px; border:1px solid #ccc; margin-bottom: 10px;}#divBtn1{background:yellowgreen;}#divBtn2{background:paleturquoise;}.div3{width:100px;height:100px;background:blueviolet}
登录后复制
js代码:
/* *javascript动态修改css效果的方法(四种) * 第一种:div1.style.width="100px"; * 第二种:div2.style.cssText="width:100px;height:100px;background: palevioletred;"; * 第三种:div1.setAttribute("class","div2")和div3.className="div3";//效果一样 * 第四种:使用更改外联的css文件,从而改变元素的css * obj.setAttribute("href","css/css2.css"); * */ function changeCss1(){ var div1=document.getElementById("divBtn1"); div1.style.width="100px"; div1.style.height="100px"; div1.style.background="red"; } function changeCss2(){ var div2=document.getElementById("divBtn2"); div2.style.cssText="width:100px;height:100px;background: palevioletred;"; //cssText会覆盖之前的设置 无兼容性问题 写法和css样式表相同 } function changeCss3(){ var div3=document.getElementById("divBtn3"); //div3.className="div3";//效果一样 div3.setAttribute("class","div3"); } function changeCss4(){ var obj=document.getElementById("cssLink"); obj.setAttribute("href","css/css2.css"); }
登录后复制
更多编程相关知识,请访问:编程视频!!
以上就是用js怎么改变css样式的详细内容,更多请关注【创想鸟】其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2712908.html