[英]How to add smooth scrolling effect on horizontal scrolling?
我剛剛看到 Vlad Danila 的回答,但無法重現平滑的滾動效果。 誰能幫我?
這是我放在一起的示例代碼片段:
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>
提前致謝!
您可以使用本機 CSS 屬性scroll-behavior: smooth
,如下所示:
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>
唯一的缺點是在 Safari 中它只適用於標志(Ref) 。 為了克服這個問題,你可以使用 ponyfill 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.