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>
相关推荐
OpenTiny社区5 分钟前
TinyRobot Skills技巧大公开:让 AI 成为你的 “UI 搭建”副驾驶
前端·vue.js·ai编程
土豆12508 分钟前
Rust 实战:手把手教你开发一个命令行工具
前端·rust
Moment12 分钟前
2026年,TypeScript还值不值得学 ❓❓❓
前端·javascript·面试
林九生15 分钟前
【Vue3】解决 Tailwind CSS v4 + Vite 8 中 `@import “tailwindcss“` 不起作用的问题
前端·css
陈随易16 分钟前
AI时代,说点心里话
前端·后端·程序员
console.log('npc')26 分钟前
Cursor,Trae,Claude Code如何协作生产出一套前后台app?
前端·人工智能·react.js·设计模式·ai·langchain·ai编程
乌拉那拉丹39 分钟前
vue3 配置跨域 (vite.config.ts中配置)
前端·vue.js
happymaker062643 分钟前
web前端学习日记——DAY01(HTML基本标签)
前端·学习·html
IMPYLH44 分钟前
Linux 的 chmod 命令
linux·运维·服务器
笨笨狗吞噬者1 小时前
【uniapp】小程序支持分包引用分包 node_modules 依赖产物打包到分包中
前端·微信小程序·uni-app