我有一个wheel
事件设置,但如果您使用的是OS X,则由于原生弹性效应,事件会继续触发。
如何防止这种弹性效果? 这是一些代码...
window.addEventListener('wheel',function(){
pxCount++;
var starContainer =
document.getElementById('starContainer').style.left = '-'+50*pxCount+'px';
});
答案 0 :(得分:1)
你可以将你的听众包裹在去抖动函数中,其目的是在给定的时间限制内只执行一次某个动作。
我是这个人的粉丝:https://davidwalsh.name/javascript-debounce-function
// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
您可能会这样使用它:
var wheelAction = debounce(function() {
pxCount++;
var starContainer =
document.getElementById('starContainer').style.left = '-'+50*pxCount+'px';
}, 250);
window.addEventListener('wheel', wheelAction);