Home >Web Front-end >JS Tutorial >JS method to realize clicking button to control Div width, heightening and background color adjustment_javascript skills
The example in this article describes how to use JS to control the width, height, and background color of a Div by clicking a button. Share it with everyone for your reference. The details are as follows:
JavaScript is used here to change the height, width and background color of the DiV after clicking the button. Click the corresponding button, and the Div adjusts the height, width, background color, etc. In terms of implementation, JS is mainly used to control the change of CSS style files after clicking the button. All this is under the dynamic control of JS, such as the implementation of switching web page styles without refreshing, which can be expanded based on this.
The operation effect is as shown below:
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> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>点击按钮改变CSS样式</title> <style type="text/css"> * { padding:0px; margin:0px; } .box { width:300px; height:300px; border:1px solid #CBC4F7; font-size:13px; margin:100px auto; } .divWidth { width:400px; } .divHeight { height:400px; } .divBgColor { background-color:#DCF3B1; } p { padding:15px 5px; } ul li { list-style:none; width:140px; height:32px; text-align:center; line-height:32px; background-color:#C4EA84; border:1px solid #9BEA75; margin:0px auto; margin-bottom:10px; cursor:pointer; background-image:-webkit-linear-gradient(top, #C4EA84, #53AC28); background-image:-moz-linear-gradient(top, #C4EA84, #53AC28); background-image:-o-linear-gradient(top, #C4EA84, #53AC28); -webkit-border-radius:4px; -moz-border-radius:4px; -o-border-radius:4px; } </style> <script type="text/javascript"> window.onload=function(){ var btn1 = document.getElementById("btn1"); var btn2 = document.getElementById("btn2"); var btn3 = document.getElementById("btn3"); funClick = function(btnID,changeClass){ btnID.onclick = function() { var boxClass = btnID.parentNode.parentNode.className; var ifClass = boxClass.indexOf(changeClass); if(ifClass < 0){ boxClass = boxClass + " " + changeClass; }else { boxClass = boxClass.replace(changeClass,""); } btnID.parentNode.parentNode.className = boxClass; } } funClick(btn1,"divWidth"); funClick(btn2,"divHeight"); funClick(btn3,"divBgColor"); } </script> </head> <body> <div class="box"> <p>这里是少许文本</p> <ul> <li id="btn1">点我调整宽度</li> <li id="btn2">点我调整高度</li> <li id="btn3">点我调整背景颜色</li> </ul> </div> </body> </html>
I hope this article will be helpful to everyone’s JavaScript programming design.