使用垂直鼠标滚轮在React组件上水平滚动 [英] Horizontal Scrolling on React Component Using Vertical Mouse Wheel

查看:834
本文介绍了使用垂直鼠标滚轮在React组件上水平滚动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个组件,当在较小的桌面窗口中时,该组件可以调整为水平的引导卡行.对于没有水平鼠标滚轮并且不使用触摸板的用户,我希望允许用户将鼠标悬停在此特定组件上时使用其垂直鼠标滚轮移动来水平滚动.

I have a component that resizes into a horizontal row of bootstrap cards when in a smaller desktop window. For users without a horizontal mouse wheel and not using a touchpad, I would like to allow users to scroll horizontally using their vertical mouse wheel movements when hovering over this particular component.

这是我原来基于以下代码的StackOverflow问题: https://stackoverflow.com/a/15343916/8387497

Here is the original StackOverflow issue I based my code off of: https://stackoverflow.com/a/15343916/8387497

Horizo​​ntal Scroll helper组件:

Horizontal Scroll helper component:

function horizontalScroll (event) {
  const delta = Math.max(-1, Math.min(1, (event.nativeEvent.wheelDelta || -event.nativeEvent.detail)))
  event.currentTarget.scrollLeft -= (delta * 10)
  event.preventDefault
}

我如何在需要水平滚动的组件上实现它:

How I've implemented it on component requiring horizontal scrolling:

<Row className='announcements-home' onWheel={horizontalScroll} >

将这个horizontalScroll辅助函数放置在React onWheel事件中后,它将水平和垂直滚动.我想要的结果只是水平滚动.此外,Firefox似乎根本不会对这些更改对水平滚动做出响应.

When I've placed this horizontalScroll helper function within the React onWheel event, it scrolls horizontally AND vertically. My desired outcome is just horizontal scrolling. Also, Firefox does not appear to respond at all to horizontal scrolling with these changes.

推荐答案

onWheel = (e) => {
    e.preventDefault()
    var container = document.getElementById('container')
    var containerScrollPosition = document.getElementById('container').scrollLeft
    container.scrollTo({
        top: 0,
        left: largeContainerScrollPosition + e.deltaY
        behaviour: 'smooth' //if you want smooth scrolling
    })
}

这篇关于使用垂直鼠标滚轮在React组件上水平滚动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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