Created
July 9, 2013 01:47
-
-
Save simplelife7/5954021 to your computer and use it in GitHub Desktop.
【JS】判断元素是否在可视区域内
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var a = document.getElementById("eq").offsetTop; | |
if (a >= $(window).scrollTop() && a < ($(window).scrollTop()+$(window).height())) { | |
alert("div在可视范围"); | |
} |
rambo-panda
commented
Jun 29, 2016
•
@rambo-panda 分享的这个方法判断的是 整个元素都在可视区域。
楼主的方法是部分, 且只判断了顶部位置,忽略了左右
@rambo-panda 分享的方法也可以改成判断元素有一部分在可视区域(包括全部在可视区域的情况),将
...
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
rect.right <= (window.innerWidth || document.documentElement.clientWidth)
...
中的 window.innerHeight
或 document.documentElement.clientHeight
加上此元素的高度即可。即
...
rect.bottom <= (window.innerHeight + el.offsetHeight || document.documentElement.clientHeight + el.offsetHeight)
...
向上滑动时,这种做法并没有效果,因此还可以这样:
...
rect.bottom <= (window.innerHeight + height || document.documentElement.clientHeight + height || window.innerHeight - height || document.documentElement.clientHeight - height)
...
由此可以制作一个函数,使其接受一个布尔值来决定是否加上该元素的高度,从而达到多用的效果。
补充一个可以返回可见比例的方法
/**
* 返回 element 的可见比例
* @param ele
* @param defaultTop 父元素的getBoundingClientRect().top
*/
export function elementInViewportRatio(ele: Element, defaultTop: number): number {
const rect = ele.getBoundingClientRect();
let { top, bottom } = rect;
const height = rect.height;
const innerHeight = window.innerHeight;
top -= defaultTop;
bottom -= defaultTop;
top = Math.abs(top);
if (bottom <= 0 || top >= innerHeight) {
return 0;
}
return Number(((innerHeight - top) / height).toFixed(2));
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment