ele.getBoundingClientRect()
此方法返回一个getClientRect
集合,包含元素距离DOM
可见视口top,left,bottom,right
属性及width
和height
属性。
注意这里的bottom
指的是元素最下面距离视口顶部的距离。
判断页面是否出现滚动条
function isScrollY() {
return document.documentElement.offsetHeight > document.documentElement.clientHeight;
}
function isScrollX() {
return document.body.offsetWidth > document.documentElement.clientWidth;
}
获取滚动条的宽度
function getScrollWidth () {
var ele = document.createElement('div');
ele.style.cssText = 'position:absolute;width:100px;height:100px;overflow:scroll;left:-1000px';
document.body.appendChild(ele);
var offsetWidth = ele.offsetWidth;
var clientWidth = ele.clientWidth;
var scrollWidth = offsetWidth-clientWidth;
document.body.removeChild(ele);
return scrollWidth;
}
判断元素是否在屏幕中即能否看见
function eleUnvisible() {
var ele = document.getElementsByClassName('div')[0];
var getBoundingClientRect = ele.getBoundingClientRect();
var scrollWidthX = isScrollX() ? getScrollWidth() : 0;
var scrollWidthY = isScrollY() ? getScrollWidth() : 0;
if (getBoundingClientRect.right < 1||
getBoundingClientRect.bottom < 1) {
return true;
}
if(getBoundingClientRect.left > (window.innerWidth - scrollWidthY) || getBoundingClientRect.top > (window.innerHeight - scrollWidthX)){
return true;
}
return false;
}
getBoundingClientRect.right<1
则元素被隐藏在屏幕左边getBoundingClientRect.bottom<1
则元素被隐藏在屏幕上边getBoundingClientRect.left > (window.innerWidth - scrollWidth)
则元素被隐藏在屏幕右边getBoundingClientRect.top > (window.innerHeight - scrollWidth)
则元素被隐藏在屏幕下边
这里用到window.innerHeight - scrollWidth
来比较因为有滚动条的话若getBoundingClientRect.top
被滚动条隐藏的话元素也是不可见的。