Any way to prevent horizontal scrolling triggering swipe back gesture on OS X Lion Safari?

后端 未结 8 1942
南笙
南笙 2021-01-30 04:09

I am working on a UI that uses horizontal scrolling in a div element (using overflow: scroll). I cannot scroll to the left, because it would start the

8条回答
  •  南方客
    南方客 (楼主)
    2021-01-30 04:40

    In modern browsers this should do the trick:

    element.addEventListener("wheel", function(event) {
      if (Math.abs(event.deltaX) < Math.abs(event.deltaY)) {
        // Scrolling more vertically than horizontally. Let it be!
        return
      }
      const scrollLeftMax = this.scrollWidth - this.offsetWidth
      if (
        this.scrollLeft + event.deltaX < 0 ||
        this.scrollLeft + event.deltaX > scrollLeftMax
      ) { 
        event.preventDefault()
      }
    }, false)
    

    Side note: Firefox has a handy scrollLeftMax property, but it's not standard, so it's better to calculate it ourselves.

提交回复
热议问题