我通过AJAX加载元素。其中一些只有当你向下滚动页面时才能看到。有什么方法可以知道元素现在是否在页面的可见部分?


当前回答

其他答案通常不检查元素是否在视图中沿着X轴,即可能在当前视口Y范围内,但不在X范围内。这个函数检查X和Y是否显示在视口中:

function checkElInView(el) {
    if (!el || !typeof el.getBoundingClientRect === "function") return false;
    const r = el.getBoundingClientRect();
    const vw = document.documentElement.clientWidth;
    const vh = document.documentElement.clientHeight;
    const inViewX = (r.left > 0 && r.left < vw) || (r.right < vw && r.right > 0);
    const inViewY = (r.top > 0 && r.top < vh) || (r.bottom < vh && r.bottom > 0);
    return inViewX && inViewY;
}

其他回答

一个基于这个答案的例子,检查一个元素是否有75%可见(即小于25%的元素在屏幕之外)。

function isScrolledIntoView(el) {
  // check for 75% visible
  var percentVisible = 0.75;
  var elemTop = el.getBoundingClientRect().top;
  var elemBottom = el.getBoundingClientRect().bottom;
  var elemHeight = el.getBoundingClientRect().height;
  var overhang = elemHeight * (1 - percentVisible);

  var isVisible = (elemTop >= -overhang) && (elemBottom <= window.innerHeight + overhang);
  return isVisible;
}

唯一适用于我的解决方案是(当$("#elementToCheck")可见时返回true):

$ (document) .scrollTop () + window.innerHeight + $ (" # elementToCheck ") .height () > $ (" # elementToCheck ") .offset直()上

我需要检查可滚动DIV容器内元素的可见性

    //p = DIV container scrollable
    //e = element
    function visible_in_container(p, e) {
        var z = p.getBoundingClientRect();
        var r = e.getBoundingClientRect();

        // Check style visiblilty and off-limits
        return e.style.opacity > 0 && e.style.display !== 'none' &&
               e.style.visibility !== 'hidden' &&
               !(r.top > z.bottom || r.bottom < z.top ||
                 r.left > z.right || r.right < z.left);
    }

更新:使用IntersectionObserver


目前为止我发现的最好的方法是jQuery appear插件。效果非常好。

模仿自定义的“appear”事件,该事件在元素滚动到视图或以其他方式对用户可见时触发。 $ (' # foo) .appear(函数(){ (美元)。文本(“Hello world”); }); 这个插件可以用来防止对隐藏的或在可视区域之外的内容的不必要请求。

我们可以在使用ES6的现代浏览器中做这样的事情:

const isFullySeen = el => el &&
  typeof el.getBoundingClientRect === 'function' &&
  el.getBoundingClientRect()['bottom'] + window.scrollY <= 
    window.innerHeight + window.scrollY && 
  el.getBoundingClientRect()['top'] + window.scrollY <= 
    window.innerHeight + window.scrollY;