js中设置样式的几种方式(setAttribute,className)

举报
小傅哥 发表于 2021/04/22 00:50:38 2021/04/22
【摘要】 以设置背景色为例子 可以用单一的backgroundColor 可以用className 可以用setAttribute(setAttribute 和 removeAttribute)为一组 实例代码(实现效果点击一个按钮,就把整个背景色替换,点击其他的就换其他的)   <html> <head> <title></title> <style type="text/...

以设置背景色为例子


可以用单一的backgroundColor
可以用className
可以用setAttributesetAttribute removeAttribute)为一组

实例代码(实现效果点击一个按钮,就把整个背景色替换,点击其他的就换其他的)

 


  
  1. <html>
  2. <head>
  3. <title></title>
  4. <style type="text/css">
  5. .bg{
  6. background-color : "blue" ;
  7. }
  8. </style>
  9. <script language="javascript" type="text/javascript">
  10. window.onload = function(){
  11. $("redC").onclick = function(){
  12. document.body.removeAttribute("className","bg");
  13. document.body.style.backgroundColor = "red";
  14. }
  15. $("blueC").onclick = function(){
  16. document.body.style.backgroundColor = "";
  17. document.body.setAttribute("className","bg");
  18. // document.body.className = "bg";
  19. }
  20. $("pinkC").onclick = function(){
  21. document.body.removeAttribute("className","bg");
  22. document.body.style.backgroundColor = "pink";
  23. }
  24. $("blackC").onclick = function(){
  25. document.body.removeAttribute("className","bg");
  26. document.body.style.backgroundColor = "black";
  27. }
  28. }
  29. function $(uid){
  30. return document.getElementById(uid);
  31. }
  32. </script>
  33. </head>
  34. <body>
  35. <input type="button" value="red" id="redC"/>
  36. <input type="button" value="blue" id="blueC"/>
  37. <input type="button" value="pink" id="pinkC"/>
  38. <input type="button" value="black" id="blackC"/>
  39. </body>
  40. </html>


 

文章来源: bugstack.blog.csdn.net,作者:小傅哥,版权归原作者所有,如需转载,请联系作者。

原文链接:bugstack.blog.csdn.net/article/details/7891697

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。