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="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