我刚刚看到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。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句