Home >Web Front-end >JS Tutorial >Javascript control dynamic change of div attributes example analysis_javascript skills
This article analyzes the method of Javascript controlling dynamic changes of div attributes. Share it with everyone for your reference. The details are as follows:
Here, JS is used to control div attribute changes, and the geometric size of the Div changes, such as becoming wider, higher, changing color, hiding the Div, resetting all attributes to default values, etc. Although in this example, changes to the values of these properties are easy to implement, in JavaScript web front-end design, this property or method is often used, so it is still worthy of everyone's attention.
The screenshot of the running effect is as follows:
The online demo address is as follows:
http://demo.jb51.net/js/2015/js-cha-div-opt-demo/
The specific code is as follows:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Javascript控制div属性变化</title> <style> #outer{width:500px;margin:0 auto;padding:0;text-align:center;} #div1{width:100px;height:100px;background:black;margin:10px auto;display:block;} </style> <script> var changeStyle = function (elem, attr, value) { elem.style[attr] = value }; window.onload = function () { var oBtn = document.getElementsByTagName("input"); var oDiv = document.getElementById("div1"); var oAtt = ["width","height","background","display","display"]; var oVal = ["200px","200px","red","none","block"]; for (var i = 0; i < oBtn.length; i++) { oBtn[i].index = i; oBtn[i].onclick = function () { this.index == oBtn.length - 1 && (oDiv.style.cssText = ""); changeStyle(oDiv, oAtt[this.index], oVal[this.index]) } } }; </script> </head> <body> <div id="outer"> <input type="button" value="变宽" /> <input type="button" value="变高" /> <input type="button" value="改变颜色" /> <input type="button" value="隐藏" /> <input type="button" value="重置" /> <div id="div1"></div> </div> </body> </html>
I hope this article will be helpful to everyone’s JavaScript programming.