简体   繁体   中英

How to scroll left-right with buttons with javascript smoothly?

I use this code to scroll my div content with left and right buttons. This simple code is very useful I can use it anywhere. So I just need to know how to scroll when these buttons smoothly. By editing this piece of javascript code can I scroll smoothly when I click the buttons?

 const buttonRight = document.getElementById('slideRight'); const buttonLeft = document.getElementById('slideLeft'); buttonRight.onclick = function () { document.getElementById('container').scrollLeft += 150; }; buttonLeft.onclick = function () { document.getElementById('container').scrollLeft -= 150; };
 #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>

You can use css scroll-behavior: smooth; on the container element:

 const rightButtons = Array.from(document.getElementsByClassName('slideRight')); const leftButtons = Array.from(document.getElementsByClassName('slideLeft')); const containers = Array.from(document.getElementsByClassName('container')); let index = 0; for (const rightButton of rightButtons) { const container = containers[index]; rightButton.addEventListener("click", function () { container.scrollLeft += 150; }); index++; } index = 0; for (const leftButton of leftButtons) { const container = containers[index]; leftButton.addEventListener("click", function () { container.scrollLeft -= 150; }); index++; }
 .container { width: 145px; height: 100px; border: 1px solid #ccc; overflow-x: scroll; scroll-behavior: smooth; }.content { width: 250px; background-color: #ccc; }
 <div class="container"> <div class="content">Click the buttons to slide horizontally!</div> </div> <button class="slideLeft" type="button">Slide left</button> <button class="slideRight" type="button">Slide right</button> <div class="container"> <div class="content">Click the buttons to slide horizontally!</div> </div> <button class="slideLeft" type="button">Slide left</button> <button class="slideRight" type="button">Slide right</button>

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