jQuery:当滚动到div的底部时使代码工作

时间:2013-05-07 17:59:09

标签: jquery

我找到了这段代码。当您滚动到整个页面的底部时它会起作用。 我想更改此代码以检测div的底部。

这是代码

$(window).data('ajaxready', true).scroll(function(){
  if ($(window).data('ajaxready') == false) return;
  if($(window).scrollTop() == $(document).height() - $(window).height()){
    var datastring=$(".passform").last().serialize();
    $('div#loadmoreajaxloader').show();
    $(window).data('ajaxready', false);
    $.ajax({
    type: "POST",
    url: "post_update.php",
    data: datastring,
    cache   : false,
    success: function(html)
    {
        if(html)
        {
            $("#update").append(html);
            $('div#loadmoreajaxloader').hide();
        }else
        {
            $('div#loadmoreajaxloader').html('<center>No more posts to show.</center>');
        }
        $(window).data('ajaxready', true);
    }
    });
}});

谢谢!

3 个答案:

答案 0 :(得分:1)

你可以这样做:

像这样获取div底部的位置:

var bottom = $('#myDiv').position().top + $('#myDiv').outerHeight(true);

$(window).scrollTop()

相比
if($(window).scrollTop() == bottom) {
    // We are the bottom of the div

答案 1 :(得分:1)

$(window).height()将给你视图端口高度,直到你可以滚动页面。

var vH = $(window).height();
$('#yourSelector').scroll(function () {
    if ($(this).scrollTop() == vH) {
        //Do ur work
    }
});

答案 2 :(得分:1)

我的想法是将它颠倒过来。

$(window).scroll(function() {
    var targetDiv = $('#div1');

    //Get the Y position of the bottom of the div
    var divBottom = (targetDiv.position().top + targetDiv.height);

    //get the top position of the scroll, minus the bottom of the div
    //and then minus the height of the window as the user can see that much
    var invertedTop = ((divBottom - $(window).scrollTop()) - $(window).height());

   //Less than or = to means we are at the bottom of the div.
   if (invertedTop <= 0) {console.log('You have reached the bottom of the target div');}
        else {console.log('You have not reached the bottom of the target div yet.');}
});