JS 图片的左右切换

图片的左右切换

复制代码
<div class="slider">
  <img src="image1.jpg" alt="Image 1">
  <img src="image2.jpg" alt="Image 2">
  <img src="image3.jpg" alt="Image 3">
</div>
<button id="prevBtn">Previous</button>
<button id="nextBtn">Next</button>

.slider {
  position: relative;
  width: 500px;
  height: 300px;
  overflow: hidden;
}

.slider img {
  width: 100%;
  height: auto;
  display: none;
}

.slider img.active {
  display: block;
}

 <script type="text/javascript">
// 获取相关元素
var slider = document.querySelector('.slider');
var prevBtn = document.getElementById('prevBtn');
var nextBtn = document.getElementById('nextBtn');
var images = slider.getElementsByTagName('img');
var currentIndex = 0;

// 显示当前图片
function showImage(index) {
  // 移除所有图片的active类
  for (var i = 0; i < images.length; i++) {
    images[i].classList.remove('active');
  }
  // 添加当前图片的active类
  images[index].classList.add('active');
}

// 点击上一张按钮
prevBtn.addEventListener('click', function() {
  currentIndex--;
  if (currentIndex < 0) {
    currentIndex = images.length - 1;
  }
  showImage(currentIndex);
});

// 点击下一张按钮
nextBtn.addEventListener('click', function() {
  currentIndex++;
  if (currentIndex >= images.length) {
    currentIndex = 0;
  }
  showImage(currentIndex);
});

// 显示初始图片
showImage(currentIndex);

</script>
相关推荐
神奇的程序员4 小时前
我的软件冲进苹果商店下载榜前 50 了
前端
阳光是sunny5 小时前
别再被 worktree 绕晕了!AI 编程时代你必须掌握的 Git 隔离神器
前端·人工智能·后端
万少6 小时前
万少的博客 - 技术分享与解决方案
前端·javascript·后端
尘世中一位迷途小书童8 小时前
用 Cesium 撸了一个森林火情监控大屏,弧线、粒子、发光效果都齐了
前端·javascript
IT_陈寒9 小时前
垃圾回收器选错了,我的Java服务内存炸了
前端·人工智能·后端
月光下的丝瓜10 小时前
Flutter 国内安装指南
前端·flutter
玄星啊10 小时前
AI 编程的第 30 天,我怀念古法 Coding 了
前端·ai编程
Jolyne_10 小时前
Angular基础速通
前端·angular.js
锋行天下11 小时前
半秒开!还有谁!!!
前端·vue.js·架构
代码搬运媛12 小时前
git 下中文文件名乱码问题解决
前端