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


当前回答

制作了一个简单的插件,用于检测元素在可滚动容器中是否可见

    $.fn.isVisible = function(){

      var win;
      if(!arguments[0])
      {
        console.error('Specify a target;');
        return false;
      }
      else
      {
        win = $(arguments[0]);
      }
      var viewport = {};
      var bounds = this.offset();
      bounds.right = bounds.left + this.outerWidth();
      bounds.bottom = bounds.top + this.outerHeight();
      viewport.bottom = win.height() + win.offset().top;
      return (!( bounds.top > viewport.bottom) && (win.offset().top < bounds.bottom));
    };

像这样调用$('elem_to_check').isVisible('scrollable_container');

希望能有所帮助。

其他回答

我在我的应用程序中有这样一个方法,但它不使用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));
}

编辑:此方法适用于I.E.(至少版本6)。请阅读评论以了解FF的兼容性。

我已经为该任务编写了一个组件,旨在以极快的速度处理大量元素(在慢速手机上处理1000个元素的时间小于10ms)。

它适用于你可以访问的所有类型的滚动容器-窗口,HTML元素,嵌入式iframe,衍生子窗口-并且非常灵活地检测什么(完全或部分可见性,边框框或内容框,自定义容差区等)。

一个巨大的、主要自动生成的测试套件可以确保它像宣传的那样跨浏览器工作。

如果你喜欢,试试吧:jQuery.isInView。否则,你可能会在源代码中找到灵感,比如这里。

Javascript代码可以写成:

窗口。addEventListener('scroll', function() { var element = document.querySelector('#main-container'); var position = element.getBoundingClientRect(); //检查是否完全可见 如果位置。顶部>= 0 &&位置。bottom <= window.innerHeight) { console.log('元素在屏幕上完全可见'); } //检查部分可见性 如果位置。顶部<窗口。innerHeight && position。底部>= 0){ console.log('元素在屏幕上部分可见'); } });

在react js中写为:

componentDidMount () { 窗口。addEventListener(“滚动”,this.isScrolledIntoView); } componentWillUnmount () { 窗口。removeEventListener(“滚动”,this.isScrolledIntoView); } isScrolledIntoView () { var element = document.querySelector('.element'); var position = element.getBoundingClientRect(); //检查是否完全可见 如果位置。顶部>= 0 &&位置。bottom <= window.innerHeight) { console.log('元素在屏幕上完全可见'); } //检查部分可见性 如果位置。顶部<窗口。innerHeight && position。底部>= 0){ console.log('元素在屏幕上部分可见'); } }

WebResourcesDepot在前段时间使用jQuery编写了一个滚动加载脚本。你可以在这里查看他们的现场演示。它们功能的关键在于:

$(window).scroll(function(){
  if  ($(window).scrollTop() == $(document).height() - $(window).height()){
    lastAddedLiveFunc();
  }
});

function lastAddedLiveFunc() { 
  $('div#lastPostsLoader').html('<img src="images/bigLoader.gif">');
  $.post("default.asp?action=getLastPosts&lastPostID="+$(".wrdLatest:last").attr("id"),
    function(data){
        if (data != "") {
          $(".wrdLatest:last").after(data);         
        }
      $('div#lastPostsLoader').empty();
    });
};

当你滚动时,你可以使用jquery插件“onScreen”来检查元素是否在当前视口中。 当选择器出现在屏幕上时,插件将选择器的":onScreen"设置为true。 这是插件的链接,你可以把它包含在你的项目中。 “http://benpickles.github.io/onScreen/jquery.onscreen.min.js”

你可以试试下面这个适合我的例子。

$(document).scroll(function() {
    if($("#div2").is(':onScreen')) {
        console.log("Element appeared on Screen");
        //do all your stuffs here when element is visible.
    }
    else {
        console.log("Element not on Screen");
        //do all your stuffs here when element is not visible.
    }
});

HTML代码:

<div id="div1" style="width: 400px; height: 1000px; padding-top: 20px; position: relative; top: 45px"></div> <br>
<hr /> <br>
<div id="div2" style="width: 400px; height: 200px"></div>

CSS:

#div1 {
    background-color: red;
}
#div2 {
    background-color: green;
}