【问题标题】:Constantly fetching vertical position of the scroll bar不断获取滚动条的垂直位置
【发布时间】:2012-10-03 15:15:57
【问题描述】:

我希望在用户达到某个文档高度时显示一个弹出窗口。例如,当读者接近帖子的结尾时,可以触发弹出窗口询问他/她的输入(评论是否喜欢帖子) 我尝试通过以下方式获取/传递文档高度:

function doch() {
    var currentscrollpos;
    if (currentscrollpos > 1500) { 
        //trigger popup
        alert(currentscrollpos);
    }
    setInterval(function() {
        currentscrollpos = $(document).scrollTop();
        return currentscrollpos;
    }, 3e3);
}​

在html函数中可以简单的通过doch()触发;

问题是,currentscrollpos的值不能从setInterval函数传递到if loop?

【问题讨论】:

    标签: jquery scrollbar scrolltop


    【解决方案1】:

    如果可以绑定到用户向下滚动页面,为什么还要使用 setInterval?

    $(window).scroll(function(){ //when a user scrolls
        if(this.pageYOffset + $(this).height() > $(document).height() - 200){ //if the scroll is within 200 px of the bottom of the page
            $('div').css('background', 'red'); //do popup
        }
    });
    

    http://jsfiddle.net/rUbwq/2/

    【讨论】:

    • 感谢您的简洁回答。但是,作为一名学习者,我可能会问为什么我的代码中 currentscrollpos 的值没有传递给 if 循环?
    • 另外我想知道为什么使用 $(this).height() 而不是 this.height()
    猜你喜欢
    • 1970-01-01
    • 2013-03-22
    • 1970-01-01
    • 2021-03-29
    • 1970-01-01
    • 2017-04-17
    • 2012-01-21
    • 1970-01-01
    • 2021-11-24
    相关资源
    最近更新 更多