简体   繁体   English

如何使用 javascript 的按钮平滑左右滚动?

[英]How to scroll left-right with buttons with javascript smoothly?

I use this code to scroll my div content with left and right buttons.我使用此代码通过左右按钮滚动我的 div 内容。 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?通过编辑这段 javascript 代码,我可以在单击按钮时平滑滚动吗?

 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;您可以使用 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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