创建一个可滚动的div,在点击事件时可以左右滚动。我想用CSS过渡或任何其他方式使滚动效果平滑,请帮助
<div class="cardsliderblock">
<div class="sliderBlock" id="Slidercontent">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>
</div>
<span class="btns horizon-prev" id="left-button"><</span>
<span class="btns horizon-next" id="right-button" >></span>
</div>
//JS
const rightBtn = document.querySelector('#right-button');
const leftBtn = document.querySelector('#left-button');
rightBtn.addEventListener("click", function(event) {
const conent = document.querySelector('#Slidercontent');
conent.scrollLeft += 150;
event.preventDefault();
});
leftBtn.addEventListener("click", function(event) {
const conent = document.querySelector('#Slidercontent');
conent.scrollLeft -= 150;
event.preventDefault();
});
// CSS
.sliderBlock {
display: flex;
height: 200px;
border: solid 1px red;
width: 800px;
overflow: hidden;
overflow-x: auto;
transition: 2s all ease;
}
.sliderBlock>div {
width: calc(100% / 5.5);
margin-right: 2.2%;
border: solid 1px black;
min-width: 143px;
}
.sliderBlock>div:nth-child(5n) {}
.btns {
display: inline-block;
width: 20px;
height: 20px;
background: red;
}
2条答案
按热度按时间djp7away1#
对于平滑滚动,您需要使用
Element.scrollTo()
方法而不是scrollLeft
属性。使用scrollTo
,您可以传递behavior
选项,将其设置为smooth
。了解有关
Element.scrollTo()
的更多信息Demo:
csga3l582#
您可以使用
字符串
使其平滑