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>
相关推荐
憧憬成为web高手5 小时前
ACTF 12307复现
前端·bootstrap·html
2401_868534785 小时前
分析RTOS与Linux有什么区别
linux·运维·服务器
wordbaby5 小时前
Axios 上传大文件崩溃:鸿蒙 RNOH 下 XHR 返回空响应头引发的"假失败"
前端·react native
wordbaby5 小时前
React Native 列表分页实战:下拉刷新与上拉加载的工程化方案
前端·react native
wordbaby6 小时前
脱离 Tab 栏的艺术:React Native 全屏子页面的导航架构实践
前端·react native·harmonyos
陈随易6 小时前
Redis 8.8发布,一定要更新
前端·后端·程序员
wordbaby7 小时前
React Native 新架构落地鸿蒙:跨三端政务级应用的工程实践与深度复盘
前端·react native·harmonyos
筠筠喵呜喵7 小时前
Linux CPU性能优化:D状态和Z状态排查与处理
linux·服务器·性能优化
Flash.kkl7 小时前
网络层协议IP、数据链路层、NAT详解
服务器·网络·网络协议·tcp/ip
excel8 小时前
为什么我推荐使用 Termius:现代 SSH 工具的完整体验
前端·后端