使用鼠标滚轮滚动滑块时如何避免页面滚动?

How to avoid page scrolling when scrolling slider with mouse wheel?

提问人:High T 提问时间:10/27/2023 更新时间:10/27/2023 访问量:54

问:

我开发了一个多图像滑块,可以用鼠标滚轮水平滚动。问题是,当我用鼠标滚轮在页面上向下滚动并到达滑块时,尽管滑块开始从右向左移动,但页面继续向下滚动。我想防止页面表单进一步滚动。当鼠标悬停在滑块上时,我试图将“溢出:隐藏”放在身体上,但随后滑块由于滚动消失并重新出现而跳跃。有没有人知道我该如何解决这个问题?先谢谢你。

  sliderWrapper.addEventListener('wheel', () => {
           
    let sliderLeft = firstImg.getBoundingClientRect().left;
    let sliderWrapperLeft =  sliderWrapper.getBoundingClientRect().left;

    let sliderRight = lastImg.getBoundingClientRect().right;
    let sliderWrapperRight =  sliderWrapper.getBoundingClientRect().right;

    function detectMouseWheelDirection(e) {
      var delta = null,
        direction = false;
      if (!e) {
        // if the event is not provided, we get it from the window object
        e = window.event;
      }
      if (e.wheelDelta) {
        // will work in most cases
        delta = e.wheelDelta / 60;
      } else if (e.detail) {
        // fallback for Firefox
        delta = -e.detail / 2;
      }
      if (delta !== null) {
        direction = delta > 0 ? 'up' : 'down';
      }

      return direction;
    }

    function handleMouseWheelDirection(direction) {
      // if mousewheel direction is down, move the slider to the left
        
       if (direction == 'down' && sliderRight > sliderWrapperRight) {
        innerSlider.style.left = --count * 15 + '%';
        // if mousewheel direction is up, move the slider to the right
      } else if (direction == 'up' && sliderLeft <= sliderWrapperLeft) {
        innerSlider.style.left = ++count * 15 + '%';
      } else {
        innerSlider.style.left = 0 + '%';
        count = 0;
      }
            
    }

   document.onmousewheel = function (e) {
      if (isMouseHover) {
          handleMouseWheelDirection(detectMouseWheelDirection(e));
      }
    };

    if (window.addEventListener) {
    document.addEventListener('DOMMouseScroll', function (e) {
        handleMouseWheelDirection(detectMouseWheelDirection(e));
      });
    }
  });
JavaScript CSS 滑块 鼠标滚轮

评论

1赞 Roko C. Buljan 10/27/2023
首先,在事件处理程序中定义函数(即在事件回调函数中)是一个非常糟糕的主意,是一种编码反模式。在根或模块作用域外部定义可重用的函数,并在需要时使用它们(调用)。"wheel"
1赞 Roko C. Buljan 10/27/2023
不要使用 CSS 属性来移动元素。请改用 CSS 。lefttranslate

答:

2赞 Isonimus 10/27/2023 #1

只需阻止事件的默认行为,并在 wheel 的 sliderWrapper 事件侦听器中传播:将其作为侦听器函数的参数传递,然后

e.preventDefault();
e.stopPropagation();

评论

1赞 Roko C. Buljan 10/27/2023
如果该页面上的 OP 有其他(自有或第三方)脚本,这些脚本非常重要,正在侦听(没有捕获阶段)怎么办?你会使其他脚本,并可能使整个 UI 失败。此外,鉴于 OP 的代码在设计上存在缺陷,您的答案也不完整。"wheel"e.stopPropagation()
0赞 Isonimus 10/27/2023
这是一个很好的观点!您能给我们任何关于如何实现OP需求的建议吗?
1赞 High T 10/27/2023
谢谢,e.preventDefault();解决了问题。这是非常基本的,我本来可以想到的。谢谢。
1赞 Isonimus 10/27/2023
很高兴我能帮上忙!