In front-end development, sometimes it is necessary to dynamically modify the style of web page elements. Here is a summary of using JS to dynamically modify the style of elements:
Page structure:
Button:
Tag: input type: button id: btn value: click me
div:
Label: div id: box
There are two ways to use JS to modify web element styles:
1. Use ClassName
2. Use Style object
The code is as follows:
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <title>DOM Style of the action element</title> 6 <style type="text/css"> 7 .box{ 8 width: 100px; 9 height: 100px; 10 background-color: red; 11 } 12 </style> 13 </head> 14 <body> 15 <input type="button" id="btn" value="Point me" /> 16 <div id="box"></div> 17 18 <!-- Add to JS Code --> 19 <script type="text/javascript"> 20 //Defined function my$-According to element id Get page elements,The purpose is to improve efficiency 21 function my$(id){ 22 return document.getElementById(id); 23 } 24 25 // Method 1.according to ClassName Change the style of an element 26 // var btn=my$('btn'); 27 // btn.onclick=function(){ 28 // my$('box').className='box'; 29 // } 30 31 //Method 2.according to Style Object to change the style of an element 32 var btn=my$('btn'); 33 btn.onclick=function(){ 34 var box=my$('box'); 35 box.style.width="100px"; 36 box.style.height="100px"; 37 box.style.backgroundColor="red"; 38 } 39 </script> 40 </body> 41 </html>
Be careful:
1. When operating styles, use the example Style ClassName or the Style object??
It is convenient to use class styles when setting multiple style properties
It is convenient to use the Style object when there are few Style properties
2. When using Style object, when meeting width and height attributes, px unit must be added
3. The value of style object property style is string
The results are as follows: