<div class="slider"> <img src="img1.jpg"> <img src="img2.jpg"> <img src="img3.jpg"> <img src="img4.jpg"> </div>
接下来,定义CSS样式,让容器的样式和位置合理:
.slider { width: 100%; height: 400px; overflow: hidden; margin: 0 auto; position: relative; } img { width: 100%; height: 400px; position: absolute; top: 0; left: 0; transition: all 0.5s ease-in-out; } img:nth-child(2) { left: 100%; } img.active { left: 0; } img.prevIoUs { left: -100%; } img.next { left: 100%; }
接下来,定义JavaScript代码:
const images = document.querySelectorAll(".slider img"); let index = 0; setInterval(() => { const prevIoUsIndex = index === 0 ? images.length - 1 : index - 1; const nextIndex = index === images.length - 1 ? 0 : index + 1; images[prevIoUsIndex].classList.remove("prevIoUs"); images[nextIndex].classList.remove("next"); images[index].classList.add("active"); images[prevIoUsIndex].classList.add("next"); images[nextIndex].classList.add("prevIoUs"); index = nextIndex; },5000);这段JavaScript代码使用setInterval循环,每次执行时改变图片的类,实现图片的滑动效果。 通过实现这段代码,我们可以实现图片滑动效果,让页面动态起来,提高用户的阅读体验,也让网站更加生动活泼。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。