跳到主要内容

元素大小宽高距离

· 阅读需 4 分钟

前言

项目开发中经常需要用到元素大小,网页高度,视口高度,各种距离等等,本文总结了获取各种宽高、距离的方法。

元素大小

祭出这几张神图,简单明了又清晰😄

各种方法总结

注意:这些方法都不考虑混杂模式,请确保你的文档在标准模式下(填写了正确的 doctype)否则获取的值会不准。

1. 获取整个网页高度与宽度

代码说明

1. 火狐不兼容 document.body,所以使用 document.documentElement

2. 理论上没有滚动条时 scrollHeight 和 clientHeight 相同,事实上各种浏览器有不同的处理,所以最保险的方法是取这俩中最大者。

function getPagearea(){
return {
width: Math.max(document.documentElement.scrollWidth,
document.documentElement.clientWidth),
height: Math.max(document.documentElement.scrollHeight,
document.documentElement.clientHeight)
}
}

PS:jq 的话  $(document).height();          $(document).width();

2. 获取视口高度与宽度

代码说明

1. 同上,火狐不兼容 document.body,所以使用 document.documentElement

function getViewport() {
   return {
    width: document.documentElement.clientWidth,
    height: document.documentElement.clientHeight
   }
}

PS:jq 的话 $(window).height();           $(window).width();

3. 获取元素距页面高度

function getElementTop(el) {
 let actualTop = el.offsetTop;
 let current = el.offsetParent;

while (current !== null) {
   actualTop += current.offsetTop;
   current = current.offsetParent;
 }
 return actualTop;
}

PS:jq 的话 jq 对象. offset().top          jq 对象. offset().left

4. 获取元素到视口的距离

使用 el.getBoundingClientRect 方法 

getBoundingClientRect 方法返回元素的大小及其相对于视口的位置。  

5. 获取纵向滚动条高度或横向滚动条长度

代码说明

同 1,火狐不兼容 document.body,所以使用 document.documentElement

function getScrollTop() {
let doc = document;
return Math.max(doc.body.scrollTop, doc.documentElement.scrollTop)
};

function getScrollLeft() {
let doc = document;
return Math.max(doc.body.scrollLeft, doc.documentElement.scrollLeft)
};

6. 获取鼠标到元素、视口、文档、屏幕距离

这种主要是读取 event 对象中的值,具体看下图比较清晰。

一个使用例子

上下滚动时判断元素在视口中出现

这个例子使用到了上面的方法

document.onscroll = () => {
let dom = document.getElementById('box');
let top = getElementTop(dom); // 元素距页面高度
let scrollTop = getScrollTop(); // 获取滚动条高度
let viewPortHeight = getViewport().height; // 获取视口宽高

if (top > scrollTop && top <= scrollTop + viewPortHeight) {
console.log('元素出现')
}
}

// 写法2:配合getBoundingClientRect判断
document.onscroll = () => {
let dom = document.getElementById('box2');
let rectTop = dom.getBoundingClientRect().top;
let viewPortHeight = getViewport().height;

if (rectTop > 0 && rectTop < viewPortHeight) {
console.log('元素出现')
}
}

// 用jq的话
document.onscroll = () => {
let $dom = $('#box');
let top = $dom.offset().top;
let scrollTop = $(window).scrollTop();
let viewPortHeight = $(window).height();

if (top > scrollTop && top <= scrollTop + viewPort.height) {
console.log('元素出现')
}
}