要实现JavaScript中的多行图片左右滚动效果,可以使用CSS动画结合JavaScript来控制图片容器的滚动。以下是一个简单的示例代码,展示了如何实现这一效果:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>图片左右滚动</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="scrolling-wrapper">
<div class="scrolling-content">
<img src="image1.jpg" alt="Image 1">
<img src="image2.jpg" alt="Image 2">
<img src="image3.jpg" alt="Image 3">
<!-- 添加更多图片 -->
</div>
</div>
<script src="script.js"></script>
</body>
</html>/* styles.css */
.scrolling-wrapper {
width: 100%;
overflow: hidden;
position: relative;
}
.scrolling-content {
display: flex;
animation: scroll 20s linear infinite;
}
.scrolling-content img {
width: 200px; /* 根据需要调整图片宽度 */
height: auto;
margin-right: 20px; /* 图片之间的间距 */
}
@keyframes scroll {
0% {
transform: translateX(0);
}
100% {
transform: translateX(-100%);
}
}// script.js
document.addEventListener('DOMContentLoaded', function() {
const scrollingContent = document.querySelector('.scrolling-content');
const images = scrollingContent.querySelectorAll('img');
const totalWidth = Array.from(images).reduce((acc, img) => acc + img.offsetWidth + 20, 0); // 计算总宽度
// 复制一份内容以实现无缝滚动
const clone = scrollingContent.cloneNode(true);
scrollingContent.parentNode.appendChild(clone);
// 调整动画持续时间以适应内容长度
const duration = (totalWidth / window.innerWidth) * 20; // 假设每秒滚动屏幕宽度的1/20
scrollingContent.style.animationDuration = `${duration}s`;
clone.style.animationDuration = `${duration}s`;
});@keyframes定义滚动动画,通过transform: translateX()实现水平移动。requestAnimationFrame优化动画性能。通过以上代码和解释,你应该能够实现一个简单的多行图片左右滚动效果。根据实际需求调整样式和逻辑即可。
没有搜到相关的文章