单个函数调用滚动事件? [英] Single function call on scroll event?
问题描述
问题前面:
如何更改此脚本,以便向上或向下滚动进行简单的单一函数调用?
Question Up Front: How can I change this script so that a neat, single function call occurs for either an up or down scroll?
这是一个 JSFiddle ,它清楚地代表了问题。
以下脚本根据用户滚动方向的方向成功推出警报:
//Firefox
$('html').on('DOMMouseScroll', function(e){
var delta = e.originalEvent.detail;
if (delta > 0) {
alert('You scrolled up');
} else if (delta < 0) {
alert('You scrolled down');
}
});
//Everything else
$('html').on('mousewheel', function(e){
var delta = e.originalEvent.wheelDelta;
if (delta < 0) {
alert('You scrolled down');
} else if (delta > 0) {
alert('You scrolled up');
}
});
但是有一个问题:
当我向上滚动或如果用户向上或向下滚动,那么该函数被多次调用,而不是仅仅整齐地执行一次。
But there's a problem: When I scroll up or down, that function is called many times, rather than just executing neatly once, if the user scrolls up or down.
所以,我的问题是:如何更改此脚本,以便向上或向下滚动发生整齐的单一函数调用?
So, my question is: How can I change this script so that a neat, single function call occurs for either an up or down scroll?
已知解决方案想法:
Underscore.js提供功能
Known Solution Idea: Underscore.js offers a function
_.debounce(<function>,delay)
但是这会导致延迟并导致错误修复。
but this causes a delay and makes for a buggy fix.
推荐答案
您可以使用基于标志的简单解决方案
You can use a simple flag based solution
var flag;
//Everything else
$('html').on('mousewheel', function (e) {
var delta = e.originalEvent.wheelDelta;
if (flag != 1 && delta < 0) {
flag = 1;
//alert('You scrolled down');
$(".notify").append("<p>You scrolled down</p>");
} else if (flag != 2 && delta > 0) {
flag = 2;
//alert('You scrolled up');
$(".notify").append("<p>You scrolled up</p>");
}
});
演示:小提琴
此外,您可以将两个处理程序组合在一起
Also you can combine both the handlers together
var flag;
$('html').on('mousewheel DOMMouseScroll', function (e) {
var delta = e.originalEvent.wheelDelta || e.originalEvent.detail;
if (flag != 1 && delta < 0) {
flag = 1;
$(".notify").append("<p>You scrolled down</p>");
} else if (flag != 2 && delta > 0) {
flag = 2;
$(".notify").append("<p>You scrolled up</p>");
}
});
演示:小提琴
这篇关于单个函数调用滚动事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!