zoukankan      html  css  js  c++  java
  • JS获取盒模型对应的宽高

    ## 获取内联样式宽高

    只能获取内联设置的样式,在style或者.css文件中设置的无法获取

    1 let div = document.querySelect('.test');
    2 let width = div.style.width
    3 let height = div.style.height

    ## currentStyle和getComputedStyle获取所有样式

    两者只能获取样式,不能设置样式

    let div = document.querySelect('.test');
    
    let width;
    
    if (div.currentStyle) {
      width = div.currentStyle.width;
    } else {
      width = window.getComputedStyle(div, null).width;
       // width = window.getComputedStyle(div, null)['width'];
       // 第二个参数可选,省略或者null
    }

    针对获取任意样式,可做兼容性处理方法:

    1 function getStyle(element, attr) {
    2   if(element.currentStyle) {
    3      return element.currentStyle[attr];
    4   } else {
    5      return getComputedStyle(element, false)[attr];
    6   }
    7 }

    至于 getBoundingClientRect()是获取相对于视窗位置的集合, 可对应获取宽高,大小, 位置。

    1 let div = document.querySelector('.test');
    2 let rectObject = div.getBoundingClientRect();

     

  • 相关阅读:
    JSTL标签
    EL(表达式语言)
    JDBC技术
    Java中的一些术语的解释
    Servlet过滤器和监听器
    MVC-初识
    EF-初识
    .NET细节知识总结,不断更新
    多线程-Task、await/async
    多线程-Thread和ThreadPool
  • 原文地址:https://www.cnblogs.com/hughes5135/p/10381260.html
Copyright © 2011-2022 走看看