js点击切换的轮播图

以下是一个简单的用JavaScript实现点击切换的轮播图的代码:

HTML部分:

复制代码
<div class="slideshow">
  <img src="image1.jpg" alt="Image 1" class="slide">
  <img src="image2.jpg" alt="Image 2" class="slide">
  <img src="image3.jpg" alt="Image 3" class="slide">
</div>
<div class="controls">
  <button class="prev">上一张</button>
  <button class="next">下一张</button>
</div>

CSS部分:

复制代码
.slideshow {
  position: relative;
}
.slide {
  display: none;
}
.controls {
  margin-top: 10px;
}

JavaScript部分:

复制代码
// 获取轮播图容器和图片元素
var slideshow = document.querySelector('.slideshow');
var slides = document.querySelectorAll('.slide');

// 获取上一张和下一张按钮
var prevButton = document.querySelector('.prev');
var nextButton = document.querySelector('.next');

// 设置初始索引和图片的显示状态
var currentIndex = 0;
slides[currentIndex].style.display = 'block';

// 点击上一张按钮时切换到前一张图片
prevButton.addEventListener('click', function() {
  slides[currentIndex].style.display = 'none';
  currentIndex = (currentIndex - 1 + slides.length) % slides.length;
  slides[currentIndex].style.display = 'block';
});

// 点击下一张按钮时切换到下一张图片
nextButton.addEventListener('click', function() {
  slides[currentIndex].style.display = 'none';
  currentIndex = (currentIndex + 1) % slides.length;
  slides[currentIndex].style.display = 'block';
});

通过上述代码,我们实现了一个简单的点击切换的轮播图。其中,点击上一张按钮会切换到前一张图片,点击下一张按钮会切换到下一张图片。当切换到第一张图片时,再点击上一张按钮会切换到最后一张图片;当切换到最后一张图片时,再点击下一张按钮会切换到第一张图片。

相关推荐
大可不必了3 小时前
03 函数定义和调用
开发语言·python
I_belong_to_jesus3 小时前
C++关于分支预测的优化1
开发语言·c++·算法
承渊政道4 小时前
【Python编程—从入门到实践】(记分与闯关:用Python+Pygame,打造越战越精彩的太空大战!)
开发语言·python·pycharm·游戏程序·pygame
爱学习的程序媛4 小时前
Python常用框架梳理
开发语言·后端·python·ai·web·后端框架·python框架
eggwyw6 小时前
Anaconda安装卸载的详细流程指南
开发语言·python
用户0044729538256 小时前
练歌镜:让眼镜听懂“循环这一句”
javascript
yuyuxun19 小时前
协同过滤的校园二手物品智能推荐系统的设计与实现 毕业设计-附源码40082
javascript·vue.js·spring boot·python·数据分析·django·课程设计
another heaven10 小时前
【C/C++ Ranges 是零开销抽象吗?拆开管道、惰性求值和编译期膨胀】
c语言·开发语言·c++
SomeOtherTime12 小时前
Rust 闭包语法和原理(AI回答)
开发语言·后端·rust
apcipot_rain12 小时前
C++转Java日记(10)
java·开发语言