zoukankan      html  css  js  c++  java
  • 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>
  • 相关阅读:
    浅谈软件开发项目的质量控制
    分布式系统稳定性模式
    正确使用 Volatile 变量
    我和 OI 的一些故事
    NOIP2020 退役记
    博弈论基础入门
    [HAOI2008]硬币购物(容斥/背包DP)
    [CF] 1307F Cow and Vacation(思维/贪心)
    [noi.ac 模拟赛8] c(容斥/DP)
    [noi.ac 模拟赛9] A.出征准备(同余最短路)
  • 原文地址:https://www.cnblogs.com/LO-ME/p/4591448.html
Copyright © 2011-2022 走看看