使用DOM操作CSS
阿新 • • 發佈:2020-12-15
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> #box1{ width: 200px; height: 200px; background-color: red ; /*background-color: red !important;*/ } </style> <script> window.onload=function(){ /* 點選按鈕以後,修改box1的大小 */ // 獲取box1 var box1=document.getElementById("box1"); //為按鈕繫結單擊響應函式 var btn01=document.getElementById("btn01"); btn01.onclick=function(){ // alert("hello");//測試 /* 修改box1的寬度 通過js修改元素的樣式 語法:元素.style.樣式名=樣式值 注意:如果CSS的樣式名中含有- 這種名稱在js中是不合法的比如background-color 需要將這種樣式名修改為駝峰命名法 去掉-,然後將-後的字母大寫 我們通過style屬性設定的樣式都是內聯樣式 而內聯樣式有較高的優先順序,所以通過js修改的樣式往往會立即顯示 但是如果在樣式中寫了 !important,則此時樣式會有最高的優先順序, 即使通過js也不能覆蓋該樣式,此時將會導致js修改樣式失效 所以儘量不要為樣式新增 !important*/ box1.style.width="300px"; box1.style.height="300px"; box1.style.backgroundColor="yellow"; }; // 點選按鈕2以後,讀取元素的樣式 var btn02=document.getElementById("btn02"); btn02.onclick=function(){ // 讀取box1的樣式 /* 語法:元素.style.樣式名 通過style屬性設定和讀取的都是內聯樣式 無法讀取樣式表中的樣式 */ alert(box1.style.width);//width用的是box1.style.width="300px";不能用樣式表中的 #box1{width: 200px;} } }; </script> </head> <body> <button id="btn01">點我一下</button> <button id="btn02">點我一下</button> <!-- div#box1 自動補全--> <div id="box1"></div> </body> </html>