滚动停止百分比时触发

时间:2014-07-30 15:39:26

标签: javascript jquery

当用户停止滚动并提醒某些消息时,我需要触发。但我需要按百分比触发它。

例如,我想向用户发出一些消息,如果他滚动,但是当他停止滚动并且他的时间超过窗口的80%时。

我有这个代码,当srcoll停止时触发,并且不知道如何使用滚动浏览器来完成这项工作:

$.fn.scrollStopped = function(callback) {           
    $(this).scroll(function(){
        var self = this, $this = $(self);
        if ($this.data('scrollTimeout')) {
            clearTimeout($this.data('scrollTimeout'));
        }
        $this.data('scrollTimeout', setTimeout(callback,250,self));
    });
};

jQuery(window).scrollStopped(function(){
    alert('stopped');
});

2 个答案:

答案 0 :(得分:2)

您可以计算文档和窗口的高度,然后将其与滚动条的当前垂直位置进行比较:

$.fn.scrollStopped = function(callback) {           
    $(this).scroll(function(){
        var self = this, $this = $(self);
        if ($this.data('scrollTimeout')) {
            clearTimeout($this.data('scrollTimeout'));
        }
        $this.data('scrollTimeout', setTimeout(callback,250,self));
    });
};

jQuery(window).scrollStopped(function(){
    console.log(jQuery(window).scrollTop());
    if($(window).scrollTop() > ($(document).height() - $(window).height())*0.8){
       alert('You have scrolled more than 80%');
    }

});

Try it yourself。您可能想要阅读有关这两个函数的更多详细信息; .scrollTop().height()

答案 1 :(得分:1)

DEMO:http://jsfiddle.net/A9dB2/

jQuery(window).scrollStopped(function(){
    var docH = $(document).height();
    var winH = $(window).height();
    var scrollTop = $(this).scrollTop()
    var totalPixels = docH - winH;

    var scrollPercentage = parseFloat(scrollTop/totalPixels * 100).toFixed(2);
    alert(scrollPercentage + "%");
});