JavaScript获取样式定义的一些小结

  使用elm.height来获取高度,你这个obj对象需要有height属性。

  但是使用elm.height来获取属性时需要注意,对于FF,你给div加上height属性,如果<div height="100">这样的,你使用alert(div.height)得到的是undefined,因为ff下div没有height这种属性,height属于自定义的属性,需要使用getAttribute('height')才能获取到自定义属性。

  但是IE下自定义的属性可以通过elm.height这样来获取到。

  想获取的是样式中定义的height属性时。如果没有在dom的属性style定义过或者用js设置过,而是在样式表中定义了属性值,直接使用elm.style.height这样得到的也是undefined。

  要获取样式表中定义的属性值,需要使用elm.currentStyle[IE}或者getComputeStyle[FF]来获取。使用这种方法比较耗时,因为要遍历样式表。

<!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>无标题文档</title>

<style type="text/css">
#myDiv
{ position:absolute;
        left
:150px;
         top
:150px;
         width
:400px;
         height
:400px;
         border
:2px solid red;
         display
:block;
   
}
</style>
</head>
<body>
<div id="myDiv"><img src="pic3.jpg" width="400px" height="400px"/></div>
<script type="text/javascript">
window.onload
=function(){
   var x=document.getElementById("myDiv")
  
if(document.all)alert(x.currentStyle.height)//IE
   else alert(window.getComputedStyle(x,null).height)
}

</script>
</body>
</html>



具体可以看
Javascript获取级联样式表中定义的CSS值

加支付宝好友偷能量挖...


原创文章,转载请注明出处:JavaScript获取样式定义的一些小结

评论(0)Web开发网
阅读(74)喜欢(0)JavaScript/Ajax开发技巧