dom元素尺寸以及位置的计算

我们经常有获取元素尺寸以及位置的需求,比如:滚动页面时获取某个img元素相对于顶部的距离

DOM元素尺寸相关的属性

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <style>
    #btn {
        width: 60px;
        height: 30px;
        line-height: 30px;
        color: #fff;
        padding: 1px;
        box-sizing: border-box;
        border: 1px red solid;
        background: #03a9f4;
    }
  </style>
</head>
<body>
  <div style="height: 700px"></div>
  <button id="btn">点击</button>
</body>
<script type="text/javascript">
  var btn = document.getElementById('btn');
  var body = document.body
  window.onscroll = function () {
    console.log('--- client ---');
    console.log('可见高度', btn.clientHeight);
    console.log('可见宽度', btn.clientWidth);
    console.log('------ offset -------');
    console.log('元素的高度', btn.offsetHeight);
    console.log('元素的宽度', btn.offsetWidth);
    console.log('偏移容器', btn.offsetParent);
    console.log('水平偏移位置', btn.offsetLeft);
    console.log('垂直偏移位置', btn.offsetTop);
    
    console.log('---- scroll -----')
    console.log('元素的整体高度', btn.scrollHeight);
    console.log('元素的整体宽度', btn.scrollWidth);
    console.log('元素左边缘与视图之间的距离', btn.scrollLeft);
    console.log('元素上边缘与视图之间的距离', btn.scrollTop);
    console.log('-----------------------end')
    
    console.log('元素的宽度', body.offsetWidth)
    console.log('元素的高度', body.offsetHeight)
    console.log('元素的整体高度', body.scrollHeight);
    console.log('元素的整体宽度', body.scrollWidth);
    console.log('元素左边缘与视图之间的距离', body.scrollLeft);
    console.log('元素上边缘与视图之间的距离', body.scrollTop);
  }
</script>
</html>

上面代码中按钮的盒子模型为:

padding: 1px;
border: 1px solid red;
width: 60px;
height: 30px;
box-sizing: border-box;
  • 元素 可见高度 可见宽度 的计算:包括 padding content 在内,不包括 border
console.log('可见高度', btn.clientHeight); // 28
console.log('可见宽度', btn.clientWidth); // 58
  • 元素 高度 宽度 的计算:包括 padding content border
console.log('元素的高度', btn.offsetHeight); // 30
console.log('元素的宽度', btn.offsetWidth); // 60
  • 元素的偏移容器 和 元素的父节元素的区别
console.log('偏移容器', btn.offsetParent); // body
  • 元素的水平以及垂直的偏移位置(与滚动条的位置无关!)
console.log('水平偏移位置', btn.offsetLeft); // 相对偏移容器顶部距离
console.log('垂直偏移位置', btn.offsetTop); // 相对偏移容器左边距离
  • 元素 scroll 相关属性的计算
scrollHeight: 无滚动条时等于 offsetHeigth, 有滚动条时包换超出的部分
scrollWidth: 无滚动条时等于 offsetWidth, 有滚动条时包换超出的部分

内容发生溢出时,元素左边缘与视图之间的距离和元素上边缘与视图之间的距离

Element.getBoundingClientRect()

该方法返回元素的大小及其相对于视口的位置,点击查看详细说明

var btn = document.getElementById('btn');
window.onscroll = function () {
  console.log(btn.getBoundingClientRect());
}

猜你喜欢

转载自www.cnblogs.com/gaollard/p/9582335.html