首页 > 解决方案 > 如何使用按钮在 div 中水平滚动设置动画

问题描述

我发现这段代码添加了在 div 中水平滚动的按钮,它是由 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>

标签: javascripthtmlcss

解决方案


添加scroll-behavior: smooth;#container.

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>


推荐阅读