简体   繁体   English

使用 jQuery 检测用户何时滚动到 div 的底部

[英]Detecting when user scrolls to bottom of div with jQuery

I have a div box (called flux) with a variable amount of content inside.我有一个 div 框(称为通量),里面有不同数量的内容。 This divbox has overflow set to auto.此 divbox 已将溢出设置为自动。

Now, what I am trying to do, is, when the use scroll to the bottom of this DIV-box, load more content into the page, I know how to do this (load the content) but I don't know how to detect when the user has scrolled to the bottom of the div tag?现在,我想做的是,当使用滚动到这个 DIV 框的底部时,将更多内容加载到页面中,我知道该怎么做(加载内容)但我不知道怎么做检测用户何时滚动到 div 标签的底部? If I wanted to do it for the entire page, I'd take.scrollTop and subtract that from.height.如果我想对整个页面执行此操作,我会使用.scrollTop 并从.height 中减去它。

But I can't seem to do that here?但我似乎不能在这里做到这一点?

I've tried taking.scrollTop from flux, and then wrapping all the content inside a div called inner, but if I take the innerHeight of flux it returns 564px (the div is set to 500 as height) and the height of 'innner' it returns 1064, and the scrolltop, when at the bottom of the div says 564.我尝试从flux中获取.scrollTop,然后将所有内容包装在一个名为inner的div中,但如果我采用flux的innerHeight,它返回564px(div设置为500作为高度)和'innner'的高度它返回 1064,当在 div 底部时,滚动顶部显示 564。

What can I do?我能做些什么?

There are some properties/methods you can use:您可以使用一些属性/方法:

$().scrollTop()//how much has been scrolled
$().innerHeight()// inner height of the element
DOMElement.scrollHeight//height of the content of the element

So you can take the sum of the first two properties, and when it equals to the last property, you've reached the end:所以你可以取前两个属性的总和,当它等于最后一个属性时,你已经到了结尾:

jQuery(function($) {
    $('#flux').on('scroll', function() {
        if($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight) {
            alert('end reached');
        }
    })
});

http://jsfiddle.net/doktormolle/w7X9N/ http://jsfiddle.net/doktormolle/w7X9N/

Edit: I've updated 'bind' to 'on' as per:编辑:我已将“绑定”更新为“打开”:

As of jQuery 1.7, the.on() method is the preferred method for attaching event handlers to a document.从 jQuery 1.7 开始,.on() 方法是将事件处理程序附加到文档的首选方法。

I found a solution that when you scroll your window and end of a div shown from bottom gives you an alert.我找到了一个解决方案,当您滚动 window 时,从底部显示的 div 的结尾会给您一个警报。

$(window).bind('scroll', function() {
    if($(window).scrollTop() >= $('.posts').offset().top + $('.posts').outerHeight() - window.innerHeight) {
        alert('end reached');
    }
});

In this example if you scroll down when div ( .posts ) finish its give you an alert.在此示例中,如果您在 div ( .posts ) 完成时向下滚动,它会给您一个警报。

Though the question was asked 5.5 years ago, still it is more than relevant in today's UI/UX context.尽管这个问题是在 5.5 年前提出的,但它在今天的 UI/UX 环境中仍然具有重要意义。 And I would like to add my two cents.我想加上我的两分钱。

var element = document.getElementById('flux');
if (element.scrollHeight - element.scrollTop === element.clientHeight)
    {
        // element is at the end of its scroll, load more content
    }

Source: https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollHeight#Determine_if_an_element_has_been_totally_scrolled资料来源: https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollHeight#Determine_if_an_element_has_been_totally_scrolled

Some elements won't allow you to scroll the full height of the element.某些元素不允许您滚动元素的整个高度。 In those cases you can use:在这些情况下,您可以使用:

var element = docuement.getElementById('flux');
if (element.offsetHeight + element.scrollTop === element.scrollHeight) {
  // element is at the end of its scroll, load more content
}

Just an additional note here as I found this when looking for a solution for a fixed div that I want to scroll.这里只是一个附加说明,因为我在寻找我想要滚动的固定 div 的解决方案时发现了这一点。 For my scenario I found that its preferable to take into account the padding on the div so I can hit the end exactly.对于我的场景,我发现最好考虑 div 上的填充,这样我就可以准确地结束。 So expanding on @Dr.Molle's answer I add the following因此,扩展@Dr.Molle 的答案,我添加了以下内容

$('#flux').bind('scroll', function() {
    var scrollPosition = $(this).scrollTop() + $(this).outerHeight();
    var divTotalHeight = $(this)[0].scrollHeight 
                          + parseInt($(this).css('padding-top'), 10) 
                          + parseInt($(this).css('padding-bottom'), 10)
                          + parseInt($(this).css('border-top-width'), 10)
                          + parseInt($(this).css('border-bottom-width'), 10);

    if( scrollPosition == divTotalHeight )
    {
      alert('end reached');
    }
  });

That'll give you the precise location, including padding and borders这将为您提供精确的位置,包括填充和边框

this worked for me though虽然这对我有用

$(window).scroll(function() {
  if ($(window).scrollTop() >= (($(document).height() - $(window).height()) - $('#divID').innerHeight())) {
    console.log('div reached');
  }
});

If you need to use this on a div that has overflow-y as hidden or scroll, something like this may be what you need.如果您需要在具有 overflow-y 作为隐藏或滚动的 div 上使用它,那么您可能需要这样的东西。

if ($('#element').prop('scrollHeight') - $('#element').scrollTop() <= Math.ceil($('#element').height())) {
    at_bottom = true;
}

I found ceil was needed because prop scrollHeight seems to round, or perhaps some other reason causing this to be off by less than 1.我发现需要 ceil 是因为 prop scrollHeight 似乎是圆形的,或者可能是其他一些原因导致它小于 1。

If you are not using Math.round() function the solution suggested by Dr.Molle will not work in some cases when a browser window has a zoom.如果您不使用 Math.round() function,当浏览器 window 具有缩放功能时,Dr.Molle建议的解决方案在某些情况下将不起作用。

For example $(this).scrollTop() + $(this).innerHeight() = 600例如 $(this).scrollTop() + $(this).innerHeight() = 600

$(this)[0].scrollHeight yields = 599.99998 $(this)[0].scrollHeight 收益率 = 599.99998

600 >= 599.99998 fails. 600 >= 599.99998 失败。

Here is the correct code:这是正确的代码:

jQuery(function($) {
    $('#flux').on('scroll', function() {
        if(Math.round($(this).scrollTop() + $(this).innerHeight(), 10) >= Math.round($(this)[0].scrollHeight, 10)) {
            alert('end reached');
        }
    })
});

You may also add some extra margin pixels if you do not need a strict condition如果您不需要严格的条件,您还可以添加一些额外的边距像素

var margin = 4

jQuery(function($) {
    $('#flux').on('scroll', function() {
        if(Math.round($(this).scrollTop() + $(this).innerHeight(), 10) >= Math.round($(this)[0].scrollHeight, 10) - margin) {
            alert('end reached');
        }
    })
});

In simple DOM usage you can check the condition在简单的 DOM 用法中,您可以检查条件

element.scrollTop + element.clientHeight == element.scrollHeight

if true then you have reached the end.如果是真的,那么你已经走到了尽头。

If anyone gets scrollHeight as undefined , then select elements' 1st subelement: mob_top_menu[0].scrollHeight如果有人将scrollHeight设为undefined ,则 select 元素的第一个子元素: mob_top_menu[0].scrollHeight

not sure if it is any help but this is how I do it.不确定这是否有帮助,但我就是这样做的。

I have an index panel that is larger that the window and I let it scroll until the end this index is reached.我有一个比 window 更大的索引面板,我让它滚动直到到达该索引的末尾。 Then I fix it in position.然后我在 position 中修复它。 The process is reversed once you scroll toward the top of the page.一旦您滚动到页面顶部,该过程就会反转。

Regards.问候。

<style type="text/css">
    .fixed_Bot {    
            position: fixed;     
            bottom: 24px;    
        }     
</style>

<script type="text/javascript">
    $(document).ready(function () {
        var sidebarheight = $('#index').height();
        var windowheight = $(window).height();


        $(window).scroll(function () {
            var scrollTop = $(window).scrollTop();

            if (scrollTop >= sidebarheight - windowheight){
                $('#index').addClass('fixed_Bot');
            }
            else {
                $('#index').removeClass('fixed_Bot');
            }                   
        });
    });

</script>

Though this was asked almost 6 years, ago still hot topic in UX design, here is demo snippet if any newbie wanted to use虽然这个问题已经问了将近 6 年,但在 UX 设计中仍然是热门话题,如果有新手想使用这里是演示片段

 $(function() { /* this is only for demonstration purpose */ var t = $('.posts').html(), c = 1, scroll_enabled = true; function load_ajax() { /* call ajax here... on success enable scroll */ $('.posts').append('<h4>' + (++c) + ' </h4>' + t); /*again enable loading on scroll... */ scroll_enabled = true; } $(window).bind('scroll', function() { if (scroll_enabled) { /* if 90% scrolled */ if($(window).scrollTop() >= ($('.posts').offset().top + $('.posts').outerHeight()-window.innerHeight)*0.9) { /* load ajax content */ scroll_enabled = false; load_ajax(); } } }); });
 h4 { color: red; font-size: 36px; background-color: yellow; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <div class="posts"> Lorem ipsum dolor sit amet Consectetuer augue nibh lacus at <br> Pretium Donec felis dolor penatibus <br> Phasellus consequat Vivamus dui lacinia <br> Ornare nonummy laoreet lacus Donec <br> Ut ut libero Curabitur id <br> Dui pretium hendrerit sapien Pellentesque <br> Lorem ipsum dolor sit amet <br> Consectetuer augue nibh lacus at <br> Pretium Donec felis dolor penatibus <br> Phasellus consequat Vivamus dui lacinia <br> Ornare nonummy laoreet lacus Donec <br> Ut ut libero Curabitur id <br> Dui pretium hendrerit sapien Pellentesque <br> Lorem ipsum dolor sit amet <br> Consectetuer augue nibh lacus at <br> Pretium Donec felis dolor penatibus <br> Phasellus consequat Vivamus dui lacinia <br> Ornare nonummy laoreet lacus Donec <br> Ut ut libero Curabitur id <br> Dui pretium hendrerit sapien Pellentesque <br> Lorem ipsum dolor sit amet <br> Consectetuer augue nibh lacus at <br> Pretium Donec felis dolor penatibus <br> Phasellus consequat Vivamus dui lacinia <br> Ornare nonummy laoreet lacus Donec <br> Ut ut libero Curabitur id <br> Dui pretium hendrerit sapien Pellentesque </div>

Here's another version.这是另一个版本。

The key code is function scroller() which takes input as the height of the div containing the scrolling section, using overflow:scroll.关键代码是 function scroller() 它将输入作为包含滚动部分的 div 的高度,使用溢出:滚动。 It approximates 5px from the top or 10px from the bottom as at the top or bottom.它大约距顶部 5 像素或距底部 10 像素,如顶部或底部。 Otherwise it's too sensitive.否则太敏感了。 It seems 10px is about the minimum.似乎 10px 大约是最小值。 You'll see it adds 10 to the div height to get the bottom height.您会看到它在 div 高度上增加了 10 以获得底部高度。 I assume 5px might work, I didn't test extensively.我认为 5px 可能会起作用,但我没有进行广泛的测试。 YMMV. YMMV。 scrollHeight returns the height of the inner scrolling area, not the displayed height of the div, which in this case is 400px. scrollHeight 返回内部滚动区域的高度,而不是 div 的显示高度,在本例中为 400px。

<?php

$scrolling_area_height=400;
echo '
<script type="text/javascript">
          function scroller(ourheight) {
            var ourtop=document.getElementById(\'scrolling_area\').scrollTop;
            if (ourtop > (ourheight-\''.($scrolling_area_height+10).'\')) {
                alert(\'at the bottom; ourtop:\'+ourtop+\' ourheight:\'+ourheight);
            }
            if (ourtop <= (5)) {
                alert(\'Reached the top\');
            }
          }
</script>

<style type="text/css">
.scroller { 
            display:block;
            float:left;
            top:10px;
            left:10px;
            height:'.$scrolling_area_height.';
            border:1px solid red;
            width:200px;
            overflow:scroll; 
        }
</style>

$content="your content here";

<div id="scrolling_area" class="scroller">
onscroll="var ourheight=document.getElementById(\'scrolling_area\').scrollHeight;
        scroller(ourheight);"
        >'.$content.'
</div>';

?>

Guys this is the solution to the zoom issue, it works with all zoom levels, in case you need it:伙计们,这是缩放问题的解决方案,它适用于所有缩放级别,以防您需要它:

if ( Math.abs(elem.offset().top) + elem.height() + elem.offset().top >= elem.outerHeight() ) {
                    console.log("bottom");
                    // We're at the bottom!
                }
            });
        }
$(window).on("scroll", function() {
    //get height of the (browser) window aka viewport
    var scrollHeight = $(document).height();
    // get height of the document 
    var scrollPosition = $(window).height() + $(window).scrollTop();
    if ((scrollHeight - scrollPosition) / scrollHeight === 0) {
        // code to run when scroll to bottom of the page
    }
});

This is the code on github.是 github 上的代码。

I have crafted this piece of code that worked for me to detect when I scroll to the end of an element!我制作了这段代码,它可以让我检测到我何时滚动到元素的末尾!

let element = $('.element');

if ($(document).scrollTop() > element.offset().top + element.height()) {

     /// do something ///
}

none of the answers worked for me, this one did:没有一个答案对我有用,这个答案:

$(window).on('scroll', function() {
    if ($(window).scrollTop() >= $('#flux').offset().top + $('#flux').outerHeight() - window.innerHeight) {
        alert('You reached the end of the DIV');
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用 React js 检测用户何时滚动到 div 的底部 - Detecting when user scrolls to bottom of div with React js 检测天气用户是否在反应js和javascript中滚动div的底部 - Detecting weather user scrolls the bottom of the div or not in react js and javascript 如何确定用户何时滚动到容器 div 的底部? 对于无限卷轴 - How to determine when user scrolls to bottom of container div? For Infinite Scroll 当用户滚动时,我希望div在页面底部滚动 - I want a div to scroll at the bottom of the page when the user scrolls 如何检测用户何时滚动到 div 的底部 - Vue - How to detect when a user scrolls to the bottom of a div - Vue 当用户滚动到页面底部时,如何启动jQuery事件? - How to start a jQuery event when the user scrolls to the bottom of the page? 当用户使用jQuery滚动时,在不同的div中触发滚动事件 - Trigger a scrolling event in a different div when a user scrolls using jQuery 滚动到div底部时获得事件? - Get an event when scrolls to bottom of a div? JQuery - 除非用户向上滚动,否则滚动并锚定到ajax驱动的div的底部 - JQuery - Scroll and anchor to bottom of ajax-driven div unless user scrolls up jQuery-滚动并锚定到ajax驱动的div的底部,除非用户向上滚动演示代码 - JQuery - Scroll and anchor to bottom of ajax-driven div unless user scrolls up with demo code
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM