【问题标题】:jQuery - Multiple events, get deltaY for one eventjQuery - 多个事件,为一个事件获取 deltaY
【发布时间】:2022-06-26 12:31:15
【问题描述】:

我使用两个事件(scrollmousewheel)。

我想为mousewheel 事件获取deltaY 来控制滑块。

变量getDelta 返回数字和undefined,尽管我在mousewheel 事件中的条件。

我想在外面获取deltaY 值。

请问怎么了?提前谢谢你。

$(window).on('scroll mousewheel', function(e) {
    if (e.type == "mousewheel") {
        var getDelta = e.deltaY;
    }

    console.log(getDelta);
}

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    如果条件,你将控制台日志放在外面。

    $(window).on('scroll mousewheel', function(e) {
           var getDelta;
        if (e.type == "mousewheel") {
             getDelta = e.deltaY;
            
        }
        
        if(getDelta)
        {
            console.log(getDelta);
    
        }else{
    
         console.log("delta is null");
    
       }
        
    
        
    }
    

    【讨论】:

    • 谢谢,但我需要把 deltaY 带到外面:-/
    • 您应该检查 delta 是否为空或从事件中获取 delta。
    【解决方案2】:

    (在我看来)使用 deltaY / X 完成任务的最佳方法是使用事件侦听器。它们可以很容易地连接和分离 - 通过人工操作或由您的应用程序/脚本生成的一些自动触发器。

    将下面的代码放在网页上,检查是否适合您。

        // Getting delta trough event listeners
        // then passing them as parameters to be consumed by other function(s)
    
        function getDelta (e) // ... starting delta events capture
        {
          // We capture here both X and Y delta values (but you can use only deltaY) because
          // some mice may have left and right buttons on the scroll wheel
          // (Logitec g502 / Razer Basilisk / etc, ...)
    
          console.log(e.deltaX + ' <- left right || up down -> ' + e.deltaY);
          doSome(e.deltaY, e.deltaX); // ... the function which will consume events
        }
    
        function startDelta ()
        {
          document.addEventListener('wheel', getDelta);
        }
    
        function stopDelta () // we stop deltaX and deltaY capture
        {
          document.removeEventListener('wheel', getDelta);
        }
    
        function doSome (y, x) // we pass events as arguments so we can use them
        {
          if (x > 0)
            console.log('some div with overflow will scroll left');
          if (x < 0)
            console.log('some div with overflow will scroll right');
          if (y > 0)
            console.log('some div with overflow will scroll up');
          if (y < 0)
            console.log('some div with overflow will scroll down');
        }
    
    </script>
    <button onclick="startDelta()"> Start Delta </button>
    &nbsp;&nbsp;
    <button onclick="stopDelta()"> Stop Delta </button>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-25
      • 1970-01-01
      • 1970-01-01
      • 2011-09-11
      相关资源
      最近更新 更多