代码描述:js获取元素样式值。js获取元素样式值简单介绍代码
本章节介绍一下如何利用javascript获取指定元素的样式属性值,这在实际应用中的使用非常的频繁。 先看一段代码实例:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="author" content="https://www.51qianduan.com/" /> <title>51前端</title> <script type="text/javascript"> window.onload=function(){ var odiv=document.getElementById("thediv"); var oshow=document.getElementById("show"); oshow.innerHTML=odiv.style.width; } </script> </head> <body> <div id="show"></div> <div id="thediv" style="width:100px;height:100px;background:red;"></div> </body> </html>
以上代码实现了我们的要求,可以获取div元素的width属性值,但是需要特别注意的是,使用odiv.style.width类似的方式只能够获取在标签内部通过style方式定义的样式,如果要获取非标签内定义的样式则需要使用其他方式。 代码实例如下:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="author" content="https://www.51qianduan.com/" /> <title>51前端</title> <style type="text/css"> #thediv{ width:100px; height:100px; background:red; } </style> <script type="text/javascript"> window.onload=function(){ var odiv=document.getElementById("thediv"); var oshow=document.getElementById("show"); function getStyle(node,property){ if(node.style[property]){ return node.style[property]; } else if(node.currentStyle){ return node.currentStyle[property]; } else if(document.defaultView&&document.defaultView.getComputedStyle){ var style=document.defaultView.getComputedStyle(node,null); return style.getPropertyValue(property); } return null; } oshow.innerHTML=getStyle(odiv,"width"); } </script> </head> <body> <div id="show"></div> <div id="thediv"></div> </body> </html>
请绑定手机号,在继续操作
注意:只有绑定手机以后,才可使用网站全部功能