滚动功能射击多而不是一次 [英] Scroll Function Firing Multiple Times Instead of Once

查看:74
本文介绍了滚动功能射击多而不是一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个网站,自动滚动到在一个单一的滚动操作每个部分。这意味着,code的检查,如果页面滚动向上或向下滚动。我相信下面的code解决我的问题,但滚动操作超过一次,而页面滚动发射多枚。你会看到,在if语句的第一个警报达到5,而不是期望1.对此事的任何帮助将是非常美联社preciated。

[注]我使用velocity.js库滚动到容器内的每个部分。

  VAR页= $(#内容容器);
VAR家庭= $(#家庭层底);
VAR音乐家= $(#音乐家);
变种运动员= $(#运动员);
VAR政治= $(#政治);
变种生物= $(#政治);
VAR页= [家,音乐家,运动员,政治,生物]变种pageCur = 0;
变种lastScrollTop = 0;
page.scroll(函数(){VAR ST = $(本).scrollTop();
变种pageNex = pageCur + 1;如果(ST> lastScrollTop){
    警报(pageNex);
页[pageNex] .velocity(滚动,{容器:$(#内容容器)});
}其他{
   警报(pageCur-1);
页[pageCur-1] .velocity(滚动,{容器:$(#内容容器)});
}
lastScrollTop = ST;
pageCur = pageNex;
});


解决方案

scroll事件(以及resize事件)火为用户做到这一点多次。为了帮助这一点,最好的做法是去抖。但是,我从来没有得到的工作。相反,我使用一个全球性的布尔值检查功能解雇了。

  VAR滚动= FALSE;
page.on(滚动,函数(){
    如果(!滚动){
        滚动= TRUE;
        //做的东西应该需要一段时间...
        滚动= FALSE;
    };
});

I am trying to create a website that automatically scrolls to each section upon a single scroll action. This means that the code has to check if the page is scrolled up or scrolled down. I believe the code below solves my problem but the scroll action is fired more than once while the page is scrolling. You will see that the first alert in the if statement reaches 5 instead of the desired 1. Any help on the matter would be highly appreciated.

[Note] I am using the velocity.js library to scroll to each section within the container.

var page = $("#content-container");
var home = $("#home-layer-bottom");
var musicians = $("#musicians");
var athletes = $("#athletes");
var politics = $("#politics");
var bio = $("#politics");
var pages = [ home,musicians,athletes,politics,bio ];

var pageCur = 0;


var lastScrollTop = 0;
page.scroll(function(){

var st = $(this).scrollTop();
var pageNex = pageCur + 1;

if (st > lastScrollTop){
    alert(pageNex);
pages[pageNex].velocity("scroll", { container: $("#content-container") });
} else {
   alert(pageCur-1);
pages[pageCur-1].velocity("scroll", { container: $("#content-container") });
}
lastScrollTop = st;
pageCur = pageNex;
});

解决方案

The scroll event (as well as the resize event) fire multiple times as a user does this. To help this, the best practice is to debounce. However, I've never gotten that to work. Instead, I use a global boolean to check if the function has fired.

var scrolled = false;
page.on('scroll', function(){
    if(!scrolled){
        scrolled = true;
        //do stuff that should take a while...
        scrolled = false;
    };
});

这篇关于滚动功能射击多而不是一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆