为scrollleft变化元素添加动画
在html元素中,scrollleft属性用于指定横向滚动条的当前位置。当你需要在动态改变scrollleft时,也可以通过平滑滚动动画来避免不自然的移动效果。
解决方案
可以通过设置scroll-behavior属性为smooth来实现平滑滚动。该属性允许浏览器在滚动时应用缓动效果。
示例代码
<div id="container"> <div id="content">click the button to slide right!</div> </div> <button id="slide" type="button">slide right</button>
#container { width: 100px; height: 100px; border: 1px solid #ccc; overflow-x: scroll; scroll-behavior: smooth; } #content { width: 250px; background-color: #ccc; }
const button = document.getElementById("slide"); button.onclick = function () { document.getElementById("container").scrollLeft += 20; };