代码描述:javascriptv 动态设置 div样式。javascript动态设置div样式
有时候需要根据需要动态设置div的样式,当然对于稍有经验的javascript开发者来说,这一切都是那么的简单,但是对于初学者或者说没有相关经验的开发者来说可能就是一个不大不小的难关,下面就通过实例简单介绍一下如何实现此效果。 代码实例如下:
<!DOCTYPE html> <html> <head> <meta charset=" utf-8"> <meta name="author" content="http://www.51qianduan.com/" /> <head> <title>动态设置div的样式-51前端</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>
请绑定手机号,在继续操作
注意:只有绑定手机以后,才可使用网站全部功能