JavaScript的DOM操作获取元素的大小

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

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

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<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" style="width:200px; height:200px; background-color: red;">测试Div</div>
</body>
</html>

 

 

通过计算获取元素的大小

通过计算获取元素的大小,无关你是否是行内、内联或者链接,它经过计算后得到的结果返回出来。
如果本身设置大小,它会返回元素的大小,如果本身没有设置,会返回默认的大小,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)只能获取到内联和链接样式的宽和高,不能获取到行内和计算后的样式。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<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-color: red;
        width:200px;
        height:200px;
    }
</style>
</head>
<body>
    <div id="box" class="aaa">测试Div</div>
</body>
</html>

 

转载于:https://www.cnblogs.com/LO-ME/p/4591448.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值