简体   繁体   English

如何水平滚动div内的元素javascript / jquery

[英]How to scroll elements inside div horizontally javascript/jquery

Description描述

I have a div with several elements inside which are in sum longer than the div itself.我有一个 div,里面有几个元素,它们的总和比 div 本身长。 See the following snippet for better understanding:请参阅以下代码段以获得更好的理解:

Code代码

 .boxSlider { width: 100%; overflow-x: auto; white-space: nowrap; display: inline-block; }.box { display: inline-block; background-color: cyan; width: 100px; }
 <div class="boxSlider"> <div class="box">Box 1</div> <div class="box">Box 2</div> <div class="box">Box 3</div> <div class="box">Box 4</div> <div class="box">Box 5</div> <div class="box">Box 6</div> <div class="box">Box 7</div> <div class="box">Box 8</div> <div class="box">Box 9</div> <div class="box">Box 10</div> </div> <input type="Button" value="Scroll left"/> <input type="Button" value="Scroll right" />

Expected output预期 output

I want to use the buttons to scroll left or right using jquery or plain javascript.我想使用按钮使用 jquery 或普通 javascript 向左或向右滚动。

You can use element.scroll(...) in order to accomplish what you want:您可以使用element.scroll(...)来完成您想要的:

Some notes:一些注意事项:

  1. Be aware browser compatilibity .注意浏览器兼容性
  2. You could simply used element.left += 50 but you lose the smooth feature which, in my opinion, is more user-friendly.你可以简单地使用element.left += 50但你失去了流畅的功能,在我看来,它对用户更友好。 In other hand, is compatible with all browsers .另一方面, 兼容所有浏览器

 const boxSlider = document.getElementById('boxSlider'); document.getElementById("btnLeft").onclick = () => { boxSlider.scroll({ left: boxSlider.scrollLeft + 100, behavior: 'smooth' }); } document.getElementById("btnRight").onclick = () => { boxSlider.scroll({ left: boxSlider.scrollLeft - 100, behavior: 'smooth' }); }
 .boxSlider { width: 100%; overflow-x: auto; white-space: nowrap; display: inline-block; }.box { display: inline-block; background-color: cyan; width: 100px; }
 <div id="boxSlider" class="boxSlider"> <div class="box">Box 1</div> <div class="box">Box 2</div> <div class="box">Box 3</div> <div class="box">Box 4</div> <div class="box">Box 5</div> <div class="box">Box 6</div> <div class="box">Box 7</div> <div class="box">Box 8</div> <div class="box">Box 9</div> <div class="box">Box 10</div> </div> <input id="btnLeft" type="Button" value="Scroll left"/> <input id="btnRight" type="Button" value="Scroll right" />

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

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