javascript - 如何使用按钮在 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>
解决方案
添加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>
推荐阅读
- android - 纹理可以在后台线程中更新但在前台线程中打印吗?
- matlab - 从长的纵向 matlab 数据中将矩阵读取为元胞数组
- lambda - Kotlin Lambda 语法解释
- jquery - 在 css 中摇一摇在 jquery 中仅持续 5 秒
- firebase - 新的 firebase 项目没有出现在 shell 上
- javascript - VSCode:从 JS url(查看 url)到 Django 视图的“转到定义”
- java - 如何使用相同的 dao 访问指向不同集合的不同存储库?
- python - 安装 Azure IoT Python SDK 的问题
- reactjs - 想要传递项目 ID 代替项目名称
- mysql - MySQL 存储过程遍历 2 个表,选择值并存储在第 3 个表中