通过style属性修改样式:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body> <h1>悼念科比</h1> <script type="text/javascript"> //通过style属性修改样式 var h1=document.querySelector("h1") h1.style.backgroundColor="pink" h1.style.fontSize="200px" //点击事件转换颜色 h1.onclick=function(){ if(h1.style.backgroundColor=="pink") {h1.style.backgroundColor="yellow"} else{h1.style.backgroundColor="pink"} } </script> </body> </html>
通过类名修改样式:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style type="text/css"> .coloryellow{ background-color: yellow; } .colorpink{ background-color: deeppink; } .none1{ display: none; } .fontsize{ font-size: 100px; } </style> </head> <body> <h1 class="coloryellow">我们都是科密!!</h1> <button id="kobe">切换样式</button> <script type="text/javascript"> var btn= document.querySelector("#kobe") var h1=document.querySelector(".coloryellow") btn.onclick=function(){ if(h1.className=="coloryellow") //当使用两个类名修改是中间用空格隔开 {h1.className="colorpink fontsize"} else{h1.className="coloryellow"} } </script> </body> </html>
创建style元素来修改样式:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body> <h1>科比在我们心中</h1> <script type="text/javascript"> var styledom=document.createElement("style") //当使用多行时要用反引号括起来 styledom.innerHTML=`.coloryellow{ background-color: yellow; } .colorpink{ background-color: deeppink; } .none1{ display: none; } .fontsize{ font-size: 100px; }` var body=document.querySelector("body") body.appendChild(styledom) var h1=document.querySelector("h1") h1.className="colorpink" </script> </body> </html>
原文地址:https://www.cnblogs.com/a155-/p/12236236.html
时间: 2024-10-27 17:26:47