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


当前回答

在这个伟大答案的基础上,你可以使用ES2015+进一步简化它:

function isScrolledIntoView(el) {
  const { top, bottom } = el.getBoundingClientRect()
  return top >= 0 && bottom <= window.innerHeight
}

如果你不关心顶部是否跳出窗口而只关心底部是否被看到,这可以简化为

function isSeen(el) {
  return el.getBoundingClientRect().bottom <= window.innerHeight
}

或者甚至是单行语句

const isSeen = el => el.getBoundingClientRect().bottom <= window.innerHeight

其他回答

我需要检查可滚动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);
    }

这个答案的一个更有效的版本:

 /**
 * Is element within visible region of a scrollable container
 * @param {HTMLElement} el - element to test
 * @returns {boolean} true if within visible region, otherwise false
 */
 function isScrolledIntoView(el) {
      var rect = el.getBoundingClientRect();
      return (rect.top >= 0) && (rect.bottom <= window.innerHeight);
 }

其他答案通常不检查元素是否在视图中沿着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;
}

如果你想在另一个div中滚动项目,

function isScrolledIntoView (elem, divID) 

{

    var docViewTop = $('#' + divID).scrollTop();


    var docViewBottom = docViewTop + $('#' + divID).height();

    var elemTop = $(elem).offset().top;
    var elemBottom = elemTop + $(elem).height();

    return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop)); 
}

更新:使用IntersectionObserver


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

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