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


当前回答

简单修改可滚动的div(容器)

var isScrolledIntoView = function(elem, container) {
    var containerHeight = $(container).height();
    var elemTop = $(elem).position().top;
    var elemBottom = elemTop + $(elem).height();
    return (elemBottom > 0 && elemTop < containerHeight);
}

注意:如果元素大于可滚动的div,则此方法无效。

其他回答

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

 /**
 * 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);
 }

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

在打印稿

  private readonly isElementInViewPort = (el: HTMLElement): boolean => {
      const rect = el.getBoundingClientRect();
      const elementTop = rect.top;
      const elementBottom = rect.bottom;
      const scrollPosition = el?.scrollTop || document.body.scrollTop;
      return (
        elementBottom >= 0 &&
        elementTop <= document.documentElement.clientHeight &&
        elementTop + rect.height > elementTop &&
        elementTop <= elementBottom &&
        elementTop >= scrollPosition
      );

};

这是我的纯JavaScript解决方案,如果它隐藏在一个可滚动的容器。

演示在这里(尝试调整窗口的大小)

var visibleY = function(el){
  var rect = el.getBoundingClientRect(), top = rect.top, height = rect.height, 
    el = el.parentNode
  // Check if bottom of the element is off the page
  if (rect.bottom < 0) return false
  // Check its within the document viewport
  if (top > document.documentElement.clientHeight) return false
  do {
    rect = el.getBoundingClientRect()
    if (top <= rect.bottom === false) return false
    // Check if the element is out of view due to a container scrolling
    if ((top + height) <= rect.top) return false
    el = el.parentNode
  } while (el != document.body)
  return true
};

编辑2016-03-26:我已经更新了解决方案,以考虑滚动过去的元素,所以它隐藏在可滚动容器的顶部。 编辑2018-10-08:更新到当滚动到屏幕上方的视图外时处理。

我找到的最简单的解决方案是交集观察者API:

var observer = new IntersectionObserver(function(entries) {
    if(entries[0].isIntersecting === true)
        console.log('Element has just become visible in screen');
}, { threshold: [0] });

observer.observe(document.querySelector("#main-container"));