以下是一个使用 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>
#scrollDiv {
width: 300px;
height: 100px;
overflow: hidden;
position: relative;
}
#scrollContent {
display: flex;
position: absolute;
left: 0;
top: 0;
transition: left 0.5s;
}
#scrollContent img {
width: 100px;
height: 100px;
margin-right: 10px;
}
</style>
</head>
<body>
<div id="scrollDiv">
<div id="scrollContent">
<img src="image1.jpg" alt="Image 1">
<img src="image2.jpg" alt="Image 2">
<img src="image3.jpg" alt="Image 3">
<img src="image4.jpg" alt="Image 4">
</div>
</div>
<button onclick="scrollLeft()">向左滚动</button>
<button onclick="scrollRight()">向右滚动</button>
<script>
let scrollAmount = 0;
const scrollContent = document.getElementById('scrollContent');
const scrollDiv = document.getElementById('scrollDiv');
const imageWidth = 100; // 每张图片的宽度(包括间距)
function scrollLeft() {
if (scrollAmount < 0) {
scrollAmount += imageWidth;
scrollContent.style.left = scrollAmount + 'px';
}
}
function scrollRight() {
if (scrollAmount > -(scrollContent.children.length - 1) * imageWidth) {
scrollAmount -= imageWidth;
scrollContent.style.left = scrollAmount + 'px';
}
}
</script>
</body>
</html>
基础概念:
scrollContent
是包含所有图片的容器,通过改变其 left
属性来实现滚动效果。scrollAmount
用于记录滚动的距离。优势:
类型:
应用场景:
常见问题及解决方法:
requestAnimationFrame
来优化动画效果。scrollLeft
和 scrollRight
函数中的边界判断条件是否正确。领取专属 10元无门槛券
手把手带您无忧上云