Sometimes it is necessary to dynamically set the style of a div as needed. Of course, for experienced javascript developers, this is all so simple, but for beginners or developers without relevant experience, it may be It’s not a big or small difficulty. Let’s briefly introduce how to achieve this effect through an example.
The code example is as follows:
<!DOCTYPE html> <html> <head> <meta charset=" utf-8"> <meta name="author" content="http://www.softwhy.com/" /> <head> <title>动态设置div的样式</title> <style type="text/css"> div{ width:50px; height:50px; background:red; margin-top:10px; } .bg{ background-color:blue; } </style> <script type="text/javascript"> window.onload=function(){ var firstDiv=document.getElementById("firstDiv"); var secondDiv=document.getElementById("secondDiv"); var first=document.getElementById("first"); var second=document.getElementById("second"); first.onclick=function(){ firstDiv.style.backgroundColor="green"; } second.onclick=function(){ secondDiv.className="bg"; } } </script> </head> <body> <div id="firstDiv"></div> <div id="secondDiv"></div> <input type="button" value="使用style方式" id="first" /> <input type="button" value="使用className方式" id="second" /> </body> </html>
The above code achieves our requirements, but uses two methods, one is the style method and the other is the className method.
Special Note:
1. When using style, word attributes such as background-color should be written in camel case (the first letter of the second word is capitalized) and written in the form backgroundColo.
2. When using className, the attribute value is the class style name, but the dot (.) cannot be added in front.
PS: How to dynamically change div attributes using JavaScript
The example in this article describes the implementation method of dynamically changing div attributes in JavaScript. Share it with everyone for your reference. The details are as follows:
Here you can dynamically change div attributes, styles, etc. through JS
<script type="text/javascript"> var oBox = document.getElementById('box'); var oDiv = document.getElementById('div1'); var aInput = document.getElementsByTagName('input'); var aAttr = ['width', 'height', 'backgroundColor', 'display', 'display']; var aValue = ['200px', '200px', 'red', 'none', 'block']; for(var len=aInput.length,i=0;i<len;i++){ aInput[i].index = i; //索引 aInput[i].onclick = function(){ //重置按钮,cssText清空DIV属性 if(this.index == aInput.length - 1)oDiv.style.cssText = ""; //设置DIV属性 property(oDiv, aAttr[this.index], aValue[this.index]); }; } //控制DIV属性 function property(obj, attr, value){ obj.style[attr] = value; } </script>
I hope this article will be helpful to everyone’s JavaScript programming design.