Smooth horizontal scroll bound to mousewheel

后端 未结 7 611
星月不相逢
星月不相逢 2020-12-29 12:08

Here is a working example of horizontal scroll with mousewheel, but it does not scroll smoothly. By smoothly I mean like ordinary vertical scroll in Firefox or Opera.

<
相关标签:
7条回答
  • 2020-12-29 13:13

    You could try to utilize the browser built in scroll behavior, by using simply scrollBy:

    const target = document.getElementsByClassName('whatever')[0];
    target.addEventListener('wheel', event => {
        event.preventDefault();
        target.scrollBy({
        left: event.deltaY*0.5,    
        behavior: 'smooth'
    });
    

    })

    It is a bit sloppy when you scroll more before the browser finished the smooth scroll (as smooth scrolling takes some time to finish the "animation"), but for some scenarios it does the job.

    You can also achieve the same essentially by settings the css property scroll-behavior: smooth, and then explicitly setting target.scrollLeft = ... on the element. Both approaches essentially use the bult-in scroll implementation of the browsers (except Safari and IE10 maybe, as those don't support this smooth behavior at all to date)

    0 讨论(0)
提交回复
热议问题