滚动后如何检查元素是否可见?

我正在通过AJAX加载元素。仅当您向下滚动页面时,其中一些才可见。
我有什么办法可以知道某个元素现在是否位于页面的可见部分?

番长村村2020/03/09 23:06:29

Simple modification for scrollable div (container)

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

NOTE: this does not work if the element is larger than the scrollable div.

小胖十三Stafan2020/03/09 23:06:29

This method will return true if any part of the element is visible on the page. It worked better in my case and may help someone else.

function isOnScreen(element) {
  var elementOffsetTop = element.offset().top;
  var elementHeight = element.height();

  var screenScrollTop = $(window).scrollTop();
  var screenHeight = $(window).height();

  var scrollIsAboveElement = elementOffsetTop + elementHeight - screenScrollTop >= 0;
  var elementIsVisibleOnScreen = screenScrollTop + screenHeight - elementOffsetTop >= 0;

  return scrollIsAboveElement && elementIsVisibleOnScreen;
}
Pro老丝2020/03/09 23:06:29

A more efficient version of this answer:

 /**
 * 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);
 }
小卤蛋村村2020/03/09 23:06:29

I have written a component for the task, designed to handle large numbers of elements extremely fast (to the tune of <10ms for 1000 elements on a slow mobile).

It works with every type of scroll container you have access to – window, HTML elements, embedded iframe, spawned child window – and is very flexible in what it detects (full or partial visibility, border box or content box, custom tolerance zone, etc).

A huge, mostly auto-generated test suite ensures that it works as advertised, cross-browser.

Give it a shot if you like: jQuery.isInView. Otherwise, you might find inspiration in the source code, e.g. here.

GreenSam2020/03/09 23:06:29

An example based off of this answer to check if an element is 75% visible (i.e. less than 25% of it is off of the screen).

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;
}
老丝达蒙2020/03/09 23:06:29

I have such a method in my application, but it does not use jQuery:

/* Get the TOP position of a given element. */
function getPositionTop(element){
    var offset = 0;
    while(element) {
        offset += element["offsetTop"];
        element = element.offsetParent;
    }
    return offset;
}

/* Is a given element is visible or not? */
function isElementVisible(eltId) {
    var elt = document.getElementById(eltId);
    if (!elt) {
        // Element not found.
        return false;
    }
    // Get the top and bottom position of the given element.
    var posTop = getPositionTop(elt);
    var posBottom = posTop + elt.offsetHeight;
    // Get the top and bottom position of the *visible* part of the window.
    var visibleTop = document.body.scrollTop;
    var visibleBottom = visibleTop + document.documentElement.offsetHeight;
    return ((posBottom >= visibleTop) && (posTop <= visibleBottom));
}

Edit : This method works well for I.E. (at least version 6). Read the comments for compatibility with FF.

猴子小小Tony2020/03/09 23:06:28
function isScrolledIntoView(elem) {
    var docViewTop = $(window).scrollTop(),
        docViewBottom = docViewTop + $(window).height(),
        elemTop = $(elem).offset().top,
     elemBottom = elemTop + $(elem).height();
   //Is more than half of the element visible
   return ((elemTop + ((elemBottom - elemTop)/2)) >= docViewTop && ((elemTop + ((elemBottom - elemTop)/2)) <= docViewBottom));
}
梅乐2020/03/09 23:06:28

isScrolledIntoView是一个非常需要的函数,因此我尝试了它,它适用于不比视口高的元素,但是如果该元素较大,则视口不起作用。要解决此问题,请轻松更改条件

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

对此:

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

在此处查看演示:http : //jsfiddle.net/RRSmQ/

村村L2020/03/09 23:06:28

这里的大多数答案都没有考虑到元素也可以隐藏,因为它滚动到div的视图之外,不仅滚动到整个页面。

为了解决这种可能性,您基本上必须检查元素是否位于其每个父元素的边界内。

该解决方案正是这样做的:

function(element, percentX, percentY){
    var tolerance = 0.01;   //needed because the rects returned by getBoundingClientRect provide the position up to 10 decimals
    if(percentX == null){
        percentX = 100;
    }
    if(percentY == null){
        percentY = 100;
    }

    var elementRect = element.getBoundingClientRect();
    var parentRects = [];

    while(element.parentElement != null){
        parentRects.push(element.parentElement.getBoundingClientRect());
        element = element.parentElement;
    }

    var visibleInAllParents = parentRects.every(function(parentRect){
        var visiblePixelX = Math.min(elementRect.right, parentRect.right) - Math.max(elementRect.left, parentRect.left);
        var visiblePixelY = Math.min(elementRect.bottom, parentRect.bottom) - Math.max(elementRect.top, parentRect.top);
        var visiblePercentageX = visiblePixelX / elementRect.width * 100;
        var visiblePercentageY = visiblePixelY / elementRect.height * 100;
        return visiblePercentageX + tolerance > percentX && visiblePercentageY + tolerance > percentY;
    });
    return visibleInAllParents;
};

它还可以让您指定在每个方向上可见的百分比。
它没有涵盖由于其他因素(例如)可能将其隐藏的可能性display: hidden

这应该在所有主流浏览器中都可以使用,因为它仅使用getBoundingClientRect我亲自在Chrome和Internet Explorer 11中对其进行了测试。

小小Sam小哥2020/03/09 23:06:28

对于我的需求,Tweeked的Scott Dowding很酷的功能-用于查找元素是否刚刚滚动到屏幕(即它的顶部边缘)中。

function isScrolledIntoView(elem)
{
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();
    var elemTop = $(elem).offset().top;
    return ((elemTop <= docViewBottom) && (elemTop >= docViewTop));
}
神无Harry2020/03/09 23:06:28

香草的答案

function isScrolledIntoView(el) {
    var rect = el.getBoundingClientRect();
    var elemTop = rect.top;
    var elemBottom = rect.bottom;

    // Only completely visible elements return true:
    var isVisible = (elemTop >= 0) && (elemBottom <= window.innerHeight);
    // Partially visible elements return true:
    //isVisible = elemTop < window.innerHeight && elemBottom >= 0;
    return isVisible;
}
老丝村村2020/03/09 23:06:28

这是我的纯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
};

EDIT 2016-03-26:我已经更新了解决方案,以解决滚动到元素上方的问题,因此该元素隐藏在可滚动容器顶部的上方。 EDIT 2018-10-08:更新为在屏幕上方滚动出视图时进行处理。