码迷,mamicode.com
首页 > 编程语言 > 详细

JavaScript的DOM_获取CSS样式设置元素大小

时间:2015-06-21 07:04:46      阅读:186      评论:0      收藏:0      [点我收藏+]

标签:

一、通过 style 内联获取元素的大小

  style 获取只能获取到行内 style 属性的 CSS 样式中的宽和高,如果有获取;如果没有则返回空。

<script type="text/javascript">
    window.onload = function(){
           var box = document.getElementById(‘box‘); //获取元素
        alert(box.style.width); //200px、 没有设置的话为空
        alert(box.style.height); //200px、没有设置的话为空
    }
</script>
</head>
<body>
    <div id="box" class="aaa" style="width:200px; height:200px;">测试Div</div>
</body>

 

 

 

 

 

 

 

二、通过计算获取元素的大小

  通过计算获取元素的大小,无关你是否是行内、内联或者链接,它经过计算后得到的结果返回出来。
   如果本身设置大小,它会返回元素的大小,如果本身没有设置,会返回默认的大小,IE6,7,8 浏览器返回 auto。

<script type="text/javascript">
    window.onload = function(){
        var style = window.getComputedStyle ? window.getComputedStyle(box, null) : null || box.currentStyle;
        alert(style.width); 
        alert(style.height); 
    }
</script>
</head>
<body>
    <div id="box" class="aaa">测试Div</div>
</body>

 

 

 

 

 

 

三、通过 CSSStyleSheet 对象中的 cssRules(或 rules)属性获取元素大小

  cssRules(或 rules)只能获取到内联和链接样式的宽和高,不能获取到行内和计算后的样式。

<script type="text/javascript">
    window.onload = function(){
           var sheet = document.styleSheets[0]; //获取 link 或 style
        var rule = (sheet.cssRules || sheet.rules)[0]; //获取第一条规则
        alert(rule.style.width); //200px、空
        alert(rule.style.height); //200px、空
    }
    
</script>
<style type="text/css">
    .aaa{
        background:#ccc;
        width:200px;
        height:200px;
    }
</style>
</head>
<body>
    <div id="box" class="aaa">测试Div</div>
</body>

 

JavaScript的DOM_获取CSS样式设置元素大小

标签:

原文地址:http://www.cnblogs.com/LO-ME/p/4591448.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!