当滚动停止百分比时触发

Trigger when scroll stopped by percent

本文关键字:百分比 滚动      更新时间:2023-09-26

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

例如,我想提醒用户一些消息,如果他滚动,但当他停止滚动,如果他滚动超过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');
});

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

$.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%');
    }
});

你自己试试。你可能想阅读更多关于这两个函数的细节;. scrolltop () and .height().

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 + "%");
});