Skip to content

Instantly share code, notes, and snippets.

@simplelife7
Created July 9, 2013 01:47
Show Gist options
  • 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在可视范围");
}
@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