Js如何获取某Dom元素的宽高

2020-07-22  本文已影响0人  刘哈哈icey

(1)dom.style.width/height 获取dom元素内联样式中设定的width,height

(2)dom.currentStyle.width/height 获取dom元素渲染后的width,height,只支持IE

(3)window.getComputedStyle(dom).width/height 浏览器渲染后的元素宽,兼容性更好

(4)dom.getBoundingClientRect().width/height/left/top/right/ 计算一个元素的绝对位置(相对于视窗左上角),它能拿到元素的left、top、right、bottom、width、height

Element.getBoundingClientRect() - Web API 接口参考 | MDN


<!DOCTYPE html>

<html lang="en">

<head>

  <meta charset="UTF-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <meta http-equiv="X-UA-Compatible" content="ie=edge">

  <title>Document</title>

  <style>

    #dom {

      height: 500px;

      width: 500px;

      background: gray;

    }

  </style>

</head>

<body>

  <div id='dom' style="width: 600px;height:400px">

  </div>

</body>

<script>

  let dom = document.getElementById('dom')

  let inlineWidth = dom.style.width; //内联样式中的width height

  console.log("内联样式中的width:", inlineWidth)

  if (dom.currentStyle) {

    let IEDomWidth = dom.currentStyle.width //这种方法获取的是浏览器渲染以后的元素的宽和高,无论是用何种方式引入的css样式都可以,但只有IE浏览器支持这种写法。

    console.log("浏览器渲染后的元素宽,仅IE支持:", IEDomWidth)

  }

  let DomWidthAfterRender = window.getComputedStyle(dom).width

  console.log("浏览器渲染后的元素宽,兼容性更好:", DomWidthAfterRender)

  let relativeViewWidth = dom.getBoundingClientRect().width

  let relativeViewLeft = dom.getBoundingClientRect().left

  console.log("计算一个元素的绝对位置(相对于视窗左上角),它能拿到元素的left、top、right、bottom、width、height:", relativeViewWidth)

  console.log("计算一个元素的绝对位置(相对于视窗左上角),它能拿到元素的left、top、right、bottom、width、height::", relativeViewLeft)

</script>

</html>

上一篇下一篇

猜你喜欢

热点阅读