我有一个 li 项目的水平列表。我希望能够单击向右箭头滚动到列表的下一个元素。应该有一个向后箭头可以向左滚动。有人可以帮我弄清楚如何使用普通 JavaScript 来做到这一点吗?
要使用普通 JavaScript 创建带有左右箭头的可滚动水平列表,您可以按照以下步骤操作。我们将使用 CSS 进行布局,使用 JavaScript 进行功能。
document.addEventListener('DOMContentLoaded', function() {
const scrollAmount = 200; // Amount of pixels to scroll per click
const container = document.querySelector('.scrollable-list');
const btnRight = document.querySelector('.scroll-btn.right');
const btnLeft = document.querySelector('.scroll-btn.left');
btnRight.addEventListener('click', function() {
container.scrollBy({ left: scrollAmount, behavior: 'smooth' });
});
btnLeft.addEventListener('click', function() {
container.scrollBy({ left: -scrollAmount, behavior: 'smooth' });
});
});
.container {
display: flex;
align-items: center;
overflow: hidden;
}
.scrollable-list {
overflow-x: auto;
white-space: nowrap;
}
.scrollable-list ul {
list-style: none;
padding: 0;
margin: 0;
display: flex;
}
.scrollable-list li {
padding: 10px;
display: inline-block;
}
.scroll-btn {
cursor: pointer;
background: #ddd;
border: none;
padding: 10px 20px;
}
.scroll-btn:hover {
background: #ccc;
}
<div class="container">
<button class="scroll-btn left"><</button>
<div class="scrollable-list">
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<!-- Add more list items as needed -->
</ul>
</div>
<button class="scroll-btn right">></button>
</div>