繁体   English   中英

jQuery:使事件仅在滚动上发生一次

[英]jQuery: Make event happen only once on scroll

我正在尝试跟踪人们如何使用jQuery在我的网站上滚动。 目前,每当有人滚动浏览页面内容的25%,50%,75%和100%时,我的代码日志消息就会发送到控制台。

如您所见,我将为每个阶段创建四个单独的函数,并使用off()函数防止事件再次触发。 但是,对我来说,这种方式似乎太过分了。 有什么更好的方法可以执行此操作而无需创建尽可能多的功能?

下面的代码工作正常(据我所知)。 我只是想知道我的工作是否有更好的解决方案?

PS。 我是一个完整的初学者,因此在回复时请考虑到这一点:)

 $(function(){ var totalHeight = $('footer').offset().top - $(window).height(); var twentyFive = Math.round(totalHeight/4); var fifty = Math.round(totalHeight/2); var seventyFive = Math.round(totalHeight*0.75); function twentyFiveFunction(){ if( $(window).scrollTop() > twentyFive ){ console.log("25 % scrolled!"); $(window).off('scroll', twentyFiveFunction); $(window).on('scroll', fiftyFunction); } } function fiftyFunction(){ if( $(window).scrollTop() > fifty ){ console.log("50 % scrolled!"); $(window).off('scroll', fiftyFunction); $(window).on('scroll', seventyFiveFunction); } } function seventyFiveFunction(){ if( $(window).scrollTop() > seventyFive ){ console.log("75 % scrolled!"); $(window).off('scroll', seventyFiveFunction); $(window).on('scroll', scrollCompleteFunction); } } function scrollCompleteFunction(){ if( $(window).scrollTop() > totalHeight ){ console.log("100 % scrolled!"); $(window).off('scroll', scrollCompleteFunction); } } $(window).on('scroll', twentyFiveFunction); }); 

使用jQuery one功能应该可以简化它。

http://api.jquery.com/one/

你不会用off各一次。

这样的事情应该起作用。

var max_scroll = 0;
var done = [false, false, false, false]
var height = $(document).height() - $(window).height();

$(window).on('scroll', function() {
    var perc = $(window).scrollTop() / height;
    if (perc <= max_scroll) return false;

    max_scroll = perc;
    var index = Math.floor(perc / 25) - 1;

    if (index >= 0 && !done[index]) {
        done[index] = true;
        console.log(((index + 1) * 25) + '% scrolled');
    }
});

感谢您较早的回复。 无论如何,我最终提出了一个好的解决方案。 所以,如果有人感兴趣,这是我想出的:

 var fired = [false, false, false, false]; $(window).on('scroll', function(){ var docHeight = Math.floor($(document).height()); var scrollTop = $(window).scrollTop() + $(window).height() + 500; for(i = 1; i < (fired.length + 1); i++){ if( ( (docHeight * 0.25 * i) < scrollTop ) && fired[i-1] == false ){ console.log(i/4*100 + "%!"); fired[i-1] = true; } } }); 

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM