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


当前回答

isScrolledIntoView是一个非常必要的函数,所以我尝试了它,它适用于不高于视口的元素,但如果元素比视口大,它就不起作用了。要解决这个问题,只需改变条件

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

:

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

请看这里的演示:http://jsfiddle.net/RRSmQ/

其他回答

这是我的纯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:更新到当滚动到屏幕上方的视图外时处理。

jQuery有一个名为inview的插件,它添加了一个新的inview事件。


下面是jQuery插件不使用事件的代码:

$.extend($.expr[':'],{
    inView: function(a) {
        var st = (document.documentElement.scrollTop || document.body.scrollTop),
            ot = $(a).offset().top,
            wh = (window.innerHeight && window.innerHeight < $(window).height()) ? window.innerHeight : $(window).height();
        return ot > st && ($(a).height() + ot) < (st + wh);
    }
});

(function( $ ) {
    $.fn.inView = function() {
        var st = (document.documentElement.scrollTop || document.body.scrollTop),
        ot = $(this).offset().top,
        wh = (window.innerHeight && window.innerHeight < $(window).height()) ? window.innerHeight : $(window).height();

        return ot > st && ($(this).height() + ot) < (st + wh);
    };
})( jQuery );

我在一个叫James的家伙的评论中发现了这一点(http://remysharp.com/2009/01/26/element-in-view-event-plugin/)

我正在寻找一种方法来查看元素是否即将进入视图,所以通过扩展上面的代码段,我设法做到了。我想我应该把这个留在这里,说不定能帮到谁

Elm =是视图中要检查的元素

scrollElement =你可以传递window或者带有滚动的父元素

Offset =如果你想让它在元素在屏幕前200px处触发,那么传递200

isscro冷景的功能(elem, scrole,抵消) { var $elem = $(elem); var $window = $); var docViewTop = $window.scrollTop(); var docViewBottom = docViewTop + $window.height(); var elemTop = $elem.抵消()top; var elemBottom = elemTop + $elem.height() 归来((elemBottom +) > = docViewBottom) &&偏移(elemTop-offset) < = docViewTop) | | ((elemBottom-offset) < = docViewBottom) && (elemTop +偏移)> = docViewTop); 的

简单修改可滚动的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,则此方法无效。

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

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