Skip to content

Instantly share code, notes, and snippets.

@simplelife7
Created July 9, 2013 01:47
Show Gist options
  • Star 16 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save simplelife7/5954021 to your computer and use it in GitHub Desktop.
Save simplelife7/5954021 to your computer and use it in GitHub Desktop.
【JS】判断元素是否在可视区域内
var a = document.getElementById("eq").offsetTop;
if (a >= $(window).scrollTop() && a < ($(window).scrollTop()+$(window).height())) {
alert("div在可视范围");
}
@rambo-panda
Copy link

rambo-panda commented Jun 29, 2016

// 分享另一个
function isElementInViewport (el) {
    var rect = el.getBoundingClientRect();
    return (
        rect.top >= 0 &&
        rect.left >= 0 &&
        rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
        rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
    );
}

@chaishi
Copy link

chaishi commented Oct 9, 2018

@rambo-panda 分享的这个方法判断的是 整个元素都在可视区域。

楼主的方法是部分, 且只判断了顶部位置,忽略了左右

@Subilan
Copy link

Subilan commented Jun 6, 2019

@rambo-panda 分享的方法也可以改成判断元素有一部分在可视区域(包括全部在可视区域的情况),将

    ...
        rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
        rect.right <= (window.innerWidth || document.documentElement.clientWidth)
    ...

中的 window.innerHeightdocument.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)
    ...

由此可以制作一个函数,使其接受一个布尔值来决定是否加上该元素的高度,从而达到多用的效果。

@wuuhw
Copy link

wuuhw commented Dec 19, 2019

补充一个可以返回可见比例的方法

/**
 * 返回 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