美文网首页
js获取元素宽高

js获取元素宽高

作者: hui_mamba | 来源:发表于2017-07-09 13:16 被阅读0次

以下面的demo为例,来展示js是如何获取一个元素的宽高的:

<style>
  div {
    width: 100px;
    height: 100px;
    padding: 50px;
    margin: 50px;
    border:50px solid;
  }
</style>
<div id="div"></div>
<script>
    var d = document.querySelector('#div');
</script>

1. window.getComputedStyle()、element.currentStyle

var ds = getComputedStyle(d);
ds.width;     //100px;
d.currentStyle.width;  //100px, 
  • IE不支持window.getComputedStyle(),支持element.currentStyle;
  • 获得计算后元素的宽高,会受到box-sizing属性的影响,默认为content-box的宽度

2. offsetHeight、offsetWidth、offsetTop、offsetLeft、officeParent

d.offsetWidth;  // 300 (number)
  • offsetHeight、offsetWidth:是border-box的宽高
  • offsetTop、offsetLeft:元素上、左外边框到包含元素(officeParent)的上内边框之间的像素距离。

3. clientWidth、clientHeight

d.clientWidth; //      200 为padding-box的宽高
document.documentElement.clientHeight; // 为视口的高度
document.body.clientHeight;   //  300 为body的高度
document.documentElement.offsetHeight  //400 为html的高度

4. scrollHeight、 scrollWidth、 scrollTop、 scrollLeft

  • scrollHeight、scrollWidth:用来获取滚动元素的宽高
  • scrollTop、 scrollLeft :被隐藏在内容区域左侧或上方的像素数

5. getBoundingClientRect()

这个方法返回一个矩形对象,包含6个属性:left、right、top、bottom、width、height。这些属性给出了元素在页面中相对于视口的位置。

var rect = d.getBoundingClientRect();
rect.left;    //50
rect.right;    //350
rect.width;    //300
rect.top;    //50
rect.bottom;    //350
rect.height;    //300

相关文章

网友评论

      本文标题:js获取元素宽高

      本文链接:https://www.haomeiwen.com/subject/cspshxtx.html