我正在尝试模仿以下网站的功能:www.verbaasd.net。每个滚动“会话”只会触发一个动作。
每次用户向下滚动时,都会发生一个动作,具体取决于变量计数的状态。我只希望每卷滚动一次。例如,如果用户拥有带触摸板的Macbook,它将会非常大量地发射多次。计数将立即从1到4。有没有办法设置超时或某些东西,以便当变量计数增加或减少1时停止0.5秒?
当前代码:
var count = 1;
$(window).on('mousewheel DOMMouseScroll', function(e) {
if (e.originalEvent.wheelDelta / 120 > 0) {
count -= 1;
} else {
count += 1;
}
if (count < 1) count = 1;
if (count > 4) count = 4;
switch (count) {
case 1:
// do something
break;
case 2:
// do something
break;
case 3:
// do something
break;
case 4:
// do something
break;
}
$(".cd-background-wrapper").attr("data-slide", count);
});
答案 0 :(得分:1)
我推荐其他方式。
你应该使用&#39; preventDefault&#39;和使用setTimeout的延迟效果。
我在链接下面写了一个简单的原型代码。 (仅在Chrome和Safari上测试过)
http://codepen.io/nigayo/pen/PNEvmY
[HTML]
<body>
<div id="wrap">
<section>section A</section>
<section>section B</section>
<section>section C</section>
<section>section D</section>
</div>
</body>
[CSS]
body {
overflow: hidden;
height: 100%;
}
#wrap {
position: relative;
width: 100%;
height: 100%;
top: 0;
}
section {
width: 100%;
height: 600px;
}
section:nth-child(1) {
background: red;
}
section:nth-child(2) {
background: blue;
}
section:nth-child(3) {
background: green;
}
section:nth-child(4) {
background: magenta;
}
[JavaScript的]
(function() {
var currentPanel = 1;
var wrap = $('#wrap');
var panelsize = 600;
var step = 10;
var interval = 1000;
var direction = 1;
var bAnimation = false;
function animation() {
setTimeout(function() {
var currentTop = parseInt(wrap.css("top"));
if (direction < 0) {
if (currentTop <= minValue) {
setTimeout(function() {
bAnimation = false;
}, interval);
return;
}
} else {
if (currentTop >= minValue) {
setTimeout(function() {
bAnimation = false;
}, interval);
return;
}
}
wrap.css({
"top": currentTop - step
});
animation();
}, 16);
}
$(window).bind('mousewheel DOMMouseScroll', function(event) {
event.preventDefault();
if (bAnimation) return;
var currentTop = parseInt(wrap.css("top"));
if (event.originalEvent.wheelDelta < 0) {
//down scroll
minValue = currentTop - panelsize;
step = 10;
direction = -1;
} else {
//up scroll
minValue = currentTop + panelsize;
step = -10;
direction = 1;
}
console.log(minValue, bAnimation);
bAnimation = true;
animation();
});
})();
如果你参考我的代码,你应该使用&#39; jquery animate function&#39;或者&#39; requestAnimationframe&#39;用于动画逻辑。
答案 1 :(得分:0)
感谢A. Wolff。在lodash.js中使用_.throttle就可以了!您可以在此处找到更多信息:https://css-tricks.com/the-difference-between-throttling-and-debouncing/