以下是一个使用原生 JavaScript 实现左右滚动列表的示例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>左右滚动列表</title>
<style>
#scrollContainer {
width: 300px;
overflow: hidden;
white-space: nowrap;
border: 1px solid #ccc;
}
#scrollContent {
display: inline-block;
}
.scrollItem {
display: inline-block;
width: 100px;
height: 50px;
background-color: #f0f0f0;
margin-right: 10px;
text-align: center;
line-height: 50px;
}
</style>
</head>
<body>
<div id="scrollContainer">
<div id="scrollContent">
<div class="scrollItem">1</div>
<div class="scrollItem">2</div>
<div class="scrollItem">3</div>
<div class="scrollItem">4</div>
<div class="scrollItem">5</div>
</div>
</div>
<button onclick="scrollLeft()">向左滚动</button>
<button onclick="scrollRight()">向右滚动</button>
<script>
const scrollContainer = document.getElementById('scrollContainer');
const scrollContent = document.getElementById('scrollContent');
let scrollPosition = 0;
function scrollLeft() {
scrollPosition -= 100; // 每次滚动的距离
if (scrollPosition < 0) {
scrollPosition = 0;
}
scrollContent.style.transform = `translateX(${scrollPosition}px)`;
}
function scrollRight() {
const maxScroll = scrollContent.offsetWidth - scrollContainer.offsetWidth;
scrollPosition += 100; // 每次滚动的距离
if (scrollPosition > maxScroll) {
scrollPosition = maxScroll;
}
scrollContent.style.transform = `translateX(${scrollPosition}px)`;
}
</script>
</body>
</html>基础概念:
transform 属性用于对元素进行旋转、缩放、移动或倾斜。translateX 函数用于沿 X 轴移动元素。优势:
transform 属性进行动画效果,可以利用 GPU 加速。类型: 常见的滚动列表实现方式还有使用定时器自动滚动、基于鼠标滚轮事件滚动等。
应用场景: 适用于需要在有限空间内展示较多项目,且希望用户能够通过简单操作查看不同项目的场景,比如商品展示、新闻列表等。
可能出现的问题及解决方法:
requestAnimationFrame 来优化动画效果。