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>
  • 相关阅读:
    adb命令(一)
    appium-DesiredCapability详解与实战
    Appium-appium日志分析
    Appium-关于appium的原生控件的 xpath 定位问题及常用方法
    Appium-xpath详解
    appium界面元素介绍
    Python3.5.1 下使用HTMLParser报错
    Python3 将configparser从ini文件中读取的内容转换成字典格式
    Django forms 关于select和checkbox设置初始选中值
    Django admin注册model究竟要怎么写才优雅
  • 原文地址:https://www.cnblogs.com/LO-ME/p/4591448.html
Copyright © 2011-2022 走看看