简体   繁体   中英

How to add smooth scrolling effect on horizontal scrolling?

I just saw an answer by Vlad Danila, but can't reproduce the smooth scrolling effect. Can anyone help me?

Here's an example code snippet I put together:

 const buttonRight = document.getElementById('slideRight'); const buttonLeft = document.getElementById('slideLeft'); buttonRight.onclick = function() { document.getElementById('container').scrollLeft += 20; }; buttonLeft.onclick = function() { document.getElementById('container').scrollLeft -= 20; };
 #container { width: 145px; height: 100px; border: 1px solid #ccc; overflow-x: scroll; } #content { width: 250px; background-color: #ccc; }
 <div id="container"> <div id="content">Click the buttons to slide horizontally!</div> </div> <button id="slideLeft" type="button">Slide left</button> <button id="slideRight" type="button">Slide right</button>

Thanks in advance!

You can use the native CSS property scroll-behavior: smooth , like so:

 const buttonRight = document.getElementById('slideRight'); const buttonLeft = document.getElementById('slideLeft'); buttonRight.onclick = function () { document.getElementById('container').scrollLeft += 20; }; buttonLeft.onclick = function () { document.getElementById('container').scrollLeft -= 20; };
 #container { width: 145px; height: 100px; border: 1px solid #ccc; overflow-x: scroll; scroll-behavior: smooth; } #content { width: 250px; background-color: #ccc; }
 <div id="container"> <div id="content">Click the buttons to slide horizontally!</div> </div> <button id="slideLeft" type="button">Slide left</button> <button id="slideRight" type="button">Slide right</button>

The only downside is that in Safari it only works with a flag (Ref) . To overcome that you can use a ponyfill .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM