Home > Article > Web Front-end > js development to dynamically modify web page element styles
This article mainly talks about code examples for modifying web page element styles with JS. It has certain reference value. Friends who are interested can learn about it. I hope it will be helpful to you after reading it.
In front-end development, sometimes the styles of web page elements need to be dynamically modified. Here is a summary of the method of dynamically modifying element styles using JS.
Webpage structure:
Button:
Label: input Type: button id: btn Value: click me
p:
Tag: p id: box
There are two ways to use JS to modify the style of web page elements:
1. Use ClassName
2. Use Style object
The code is as follows:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>DOM操作元素的样式</title> <style type="text/css"> .box{ width: 100px; height: 100px; background-color: red; } </style> </head> <body> <input type="button" id="btn" value="点 我" /> <div id="box"></div> <!-- 添加JS代码 --> <script type="text/javascript"> //定义函数my$-根据元素id获得页面元素,目的是为了提高效率 function my$(id){ return document.getElementById(id); } // 方法1.根据ClassName修改元素的样式 // var btn=my$('btn'); // btn.onclick=function(){ // my$('box').className='box'; // } //方法2.根据Style对象修改元素的样式 var btn=my$('btn'); btn.onclick=function(){ var box=my$('box'); box.style.width="100px"; box.style.height="100px"; box.style.backgroundColor="red"; } </script> </body> </html>
Related tutorials: HTML video tutorial
Note:
1. When operating styles, use example style ClassName or Style Object? ?
When setting multiple style attributes, it is convenient to use class styles
When setting fewer style attributes, it is more convenient to use Style objects
2. When using Style objects When encountering the width and height attributes, you must add the px unit
3. The value of the Style object attribute style is a string
The result is as shown in the figure:
Related tutorials: js video tutorial
The above is the detailed content of js development to dynamically modify web page element styles. For more information, please follow other related articles on the PHP Chinese website!