jQuery - 当用户离开页面时,如果他们没有滚动到底部,则显示消息

时间:2012-12-11 21:10:46

标签: jquery scroll

jQuery的新功能,无法获得此代码的最后一部分。我试图在用户离开页面时显示一个简单的提醒,如果他们没有通过滚动到底部看到所有页面内容,请点击链接。

我不确定它是否应该阻止用户进入下一页,但是现在我只想获得检测用户是否到达底部并使其与代码一起使用的部分我有。我已经有一块可以检测到是否有滚动条并且当用户将其置于底部时如何注册:

jQuery的:

        <script>
        $(document).ready(function() {
            var verticalScrollPresent = function() {
                return document.documentElement.scrollHeight !== document.documentElement.clientHeight;
            }

            $('#nav').click(function() {
                if (verticalScrollPresent) {
//imagining that this is where the code will go, but how can I register that the user     has scrolled to the bottom?
                        alert("There's a whole bunch of stuff you haven't seen yet!");
                }
            });
        });

    </script>

HTML

<a id="nav" href="http://google.com">Next page</a>

1 个答案:

答案 0 :(得分:3)

将变量设置为false,当用户滚动到底部时,将变量设置为true,在用户单击链接时检查该变量:

<script type = "text/javascript"> 
    $(document).ready(function() {
        var beenToBottom = false;
        $(window).on('scroll', function() {
            //guesstimated scrolled to bottom, adjust as neccessary
            if (($(this).scrollTop() + $(this).height() + 200) > $(document).height()) {
                beenToBottom = true;
            }
        });

        $('#nav').click(function(e) {
            e.preventDefault();
            if (!beenToBottom) {
                alert("There's a whole bunch of stuff you haven't seen yet!");
            }else{
                document.location.href = this.href;
            }
        });
    });
</script>​