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>
相关推荐
JeffongTan3 小时前
在LWC中镶嵌VF Page获取用户IP
前端·javascript·salesforce
毕竟是shy哥4 小时前
vs code连接远程服务器docker环境及配置免密登录
服务器·docker·vs code
徐小黑ACG5 小时前
nginx配置文件
linux·服务器·nginx
新时代牛马5 小时前
Linux VFS 完整篇:从path_openat、dentry/inode 到page cache 与挂载排障
linux·运维·服务器
陆枫Larry5 小时前
Astro 是什么
前端
是立不是利6 小时前
写给设计师的 CSS 博客美学指南
前端·css
新时代牛马7 小时前
Linux 驱动中断与定时完整篇:从 request_threaded_irq 到hrtimer 选型与排障
linux·运维·服务器
默_笙7 小时前
🏝 Docker 就是"房地产开发":从施工图纸到小区物业的容器化指南
前端·javascript
计算机魔术师7 小时前
Rohan Paul 谈用时间跨度衡量智能体能力,并引用 OpenAI 自动化研究实习生里程碑
前端
kyriewen7 小时前
我手写了个极简版 React Router——才搞懂 v6 为什么砍了这么多 API
前端·javascript·程序员