鼠标滚轮多次射击

时间:2018-04-28 01:38:54

标签: javascript jquery html css

当用户滚动时,如何使鼠标滚轮功能仅触发一次而不是多次(多次)。

到目前为止,这是我的工作,

$(window).bind('mousewheel', function(event) {
console.log("fire")
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>
<image src="https://cdn.dribbble.com/users/77760/screenshots/2042501/attachments/363345/potato-4.jpg"></image>

4 个答案:

答案 0 :(得分:1)

我找到了从here检测滚动结束的逻辑,如果滚动不是延迟250ms那么它将作为滚动结束

&#13;
&#13;
required prop "to" not found
&#13;
var i = 0;
$(window).bind('mousewheel', function(event) {
if(i==0){
console.log("fist time")
i++;
}
clearTimeout($.data(this, 'scrollTimer'));
    $.data(this, 'scrollTimer', setTimeout(function() {
        // do something
        console.log("Haven't scrolled in 250ms!");
        i = 0;
    }, 250));
    
})
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您可以设置eventListener并在触发后立即将其删除,如下所示:

$(window).on("mousewheel", function(e){
  console.log("only alerting once");
  $(window).unbind("mousewheel");
});

答案 2 :(得分:0)

您将要限制滚动事件以确保它不会继续触发。以下是节流功能示例:

const throttle = (func, limit) => {
  let inThrottle
  return function() {
    const args = arguments
    const context = this
    if (!inThrottle) {
      func.apply(context, args)
      inThrottle = true
      setTimeout(() => inThrottle = false, limit)
    }
  }
}

您只允许每隔x毫秒触发一次滚动事件。其中limit设置允许事件再次触发之前等待的时间(以毫秒为单位)。还有一些库提供此类功能,例如lodashRxJs

一个有用的链接:http://underscorejs.org/#throttle

节气门功能取自:https://codeburst.io/throttling-and-debouncing-in-javascript-b01cad5c8edf

答案 3 :(得分:-1)

如果用户已滚动或未滚动,您可以定义一个变量来保存该值,将其设置为false,然后在用户滚动后将其设置为true。

另请注意,从jQuery 3.0开始,.bind()已被弃用。现在最好使用.on()代替。

.on()一直是将事件处理程序附加到文档的方法,因为jquery版本为1.7

 var scrolled = false;
    $(window).on('mousewheel', function(event) {
    	if(scrolled === false) { 
        console.log('fire');
        scrolled = true;
    	}
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>
<image src="https://cdn.dribbble.com/users/77760/screenshots/2042501/attachments/363345/potato-4.jpg"></image>