以下是一个实现左右滚动的简单 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">
<style>
#scrollContainer {
width: 300px;
overflow: hidden;
white-space: nowrap;
}
.scrollItem {
display: inline-block;
width: 100px;
height: 100px;
background-color: lightblue;
margin-right: 10px;
}
</style>
</head>
<body>
<div id="scrollContainer">
<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>
<button onclick="scrollLeft()">向左滚动</button>
<button onclick="scrollRight()">向右滚动</button>
<script>
const container = document.getElementById('scrollContainer');
const containerWidth = container.offsetWidth;
let scrollPos = 0;
function scrollLeft() {
scrollPos -= 50;
if (scrollPos < - (container.scrollWidth - containerWidth)) {
scrollPos = - (container.scrollWidth - containerWidth);
}
container.style.transform = `translateX(${scrollPos}px)`;
}
function scrollRight() {
scrollPos += 50;
if (scrollPos > 0) {
scrollPos = 0;
}
container.style.transform = `translateX(${scrollPos}px)`;
}
</script>
</body>
</html>
基础概念:
transform
属性来实现元素的位移,通过对容器设置 translateX
的值来达到滚动的效果。优势:
应用场景:
如果遇到滚动不流畅或者滚动位置计算错误的问题,可能是以下原因:
解决方法:
领取专属 10元无门槛券
手把手带您无忧上云