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>
相关推荐
GuWenyue12 小时前
放弃云端API!一套React+WebGPU本地LLM方案,零数据上传、离线可用
前端·人工智能·前端框架
海阔天空任鸟飞~13 小时前
Linux 权限 777
linux·运维·服务器
原则猫13 小时前
函数/变量提升
前端
独泪了无痕14 小时前
Vue3 Hooks使用实战解析
前端·vue.js
shawxlee16 小时前
vue3在public下封装config.js自定义配置动态数据,可在打包后直接修改,方便后端部署及后续维护
前端·javascript·经验分享·vue·团队开发·js·项目优化
Kina_C16 小时前
Linux iptables 防火墙原理与实操——从四表五链到 NAT 配置
linux·运维·服务器·iptables
用户0595401744616 小时前
把记忆存储的回归测试从手工换成 Playwright + GitHub Actions,线上缺陷降低 80%
前端·css
触底反弹16 小时前
🚀 从 DOM0 级到 React 合成事件:前端事件监听的 20 年演进史
前端·react.js·面试
kyriewen16 小时前
我给前端项目的接口请求套了6层保护——才发现以前一直在裸奔
前端·javascript·面试
颜酱16 小时前
04 | 召回前置准备:搭好召回所需的四个数据库
前端·人工智能·后端