使用jQuery检测每个实例的鼠标滚动,而不是每次点击 [英] Using jQuery to detect a mouse scroll per instance, not per click

查看:59
本文介绍了使用jQuery检测每个实例的鼠标滚动,而不是每次点击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试做的是在用户向上或向下滚动时移动元素。我在一个名为goTo()的函数中有这个机制。我也试图通过使用变量来跟踪用户的位置。当用户向上或向下滚动时,变量上升或下降一。这是我的函数到目前为止的样子:

What I'm attempting to do is move an element while a user scrolls up or down. I have the mechanics of this within a function called goTo(). I am also trying to track where the user is by using a variable. When the user scrolls up or down, the variable goes up or down by one. This is what my function looks like so far:

$(window).on('DOMMouseScroll mousewheel', function(event){

 clearTimeout($.data(this, 'timer')); // NEW CODE 

 $.data(this, 'timer', setTimeout(function() { // NEW CODE

    if( event.originalEvent.wheelDelta > 0 || event.originalEvent.detail < 0 )
    {
        --curScl;
        goTo(curScl);

    } else {
        ++curScl;
        goTo(curScl);
    }

 }, 250)); // NEW CODE 

});

更新:根据@Bart Jedrocha的建议,我添加了 setTimeout 使用每个滚动来保持 curSel 的价值的包装器。但是,在执行滚动和元素移动之间存在延迟。感觉非常不自然。有没有办法在没有延迟的情况下做到这一点?

UPDATE: Per the advice of @Bart Jedrocha, I've added a setTimeout wrapper that keeps the value of curSel from skyrocketing with every scroll. However, there is a delay between when the scroll is executed, and when the element moves. It feels very unnatural. Is there a way to do this without the delay?

推荐答案

虽然 setTimeout 技术上工作,用户滚动鼠标和页面滚动之间有一点延迟。这感觉不自然并且变得烦人。因此,我需要另一种解决方案。

Though setTimeout does technically work, there is a slight delay between when the user scrolls their mouse and when the page scrolls. This feels unnatural and gets annoying. Thus, I needed another solution.

var scl=0; // Create a variable

window.setInterval(function(){
   scl=0; // Reset this variable every 1.5 seconds
}, 1500);

$(window).on('DOMMouseScroll mousewheel', function (e) { 
// Detect movement on the scrollwheel anywhere in browser window

if(e.originalEvent.detail > 0 || e.originalEvent.wheelDelta < 0) {

    while(scl==0) { 
    // Create a while loop that only executes while your variable equals 0

        // CODE HERE            

        scl++; // Make your variable equal 1 after executing once
    }

} else {

    while(scl==0) { 
    // Same deal, but this time while the user scrolls down

       // CODE HERE

        scl++;
    }

}

});

这似乎没有问题。如果有人看到可以清理一下的地方,请告诉我。谢谢!

This seems to work without a problem. If anyone sees a spot where this can be cleaned up a bit, please let me know. Thanks!

这篇关于使用jQuery检测每个实例的鼠标滚动,而不是每次点击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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