js修改樣式屬性的兩種方式
阿新 • • 發佈:2021-10-11
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>07-修改樣式屬性</title> <style> .one { width: 50px; height: 50px; background-color: skyblue;} .two { width: 50px; height: 50px; background-color: purple; } .change { background-color: pink; } </style> </head> <body> <div id="one" class="one">1</div> <div id="two" class="two">2</div> <script> //方式1 const one = document.querySelector('#one'); one.onclick = function () { // 這種方式是直接新增到div的內聯樣式 this.style.backgroundColor = 'red'; } // 方式2 const two = document.querySelector('#two'); two.addEventListener('click', function () { // 這種方式會直接覆蓋原來的class選擇器 this.className = 'change'; // 如果想要保留之前的,那麼可以寫成: // this.className = 'two change'; }) </script> </body> </html>