如何通过点击按钮修改img标签src属性切换多张本地图片
实现方案
使用原生JavaScript即可实现该功能,无需引入第三方依赖,具体实现如下:
完整可运行代码
<!-- 原有图片结构 --> <div id="main_photo"> <img class="card-img-top" src="/img/new0.JPG" alt="Avatar" > </div> <!-- 原有切换按钮 --> <button id="changeimg">Change</button> <script> // 初始化当前图片索引,初始值0对应默认展示的new0.JPG let currentIndex = 0 // 最大图片索引,对应new6.JPG const maxIndex = 6 // 提前获取DOM元素,避免每次点击重复查询 const targetImg = document.querySelector('#main_photo .card-img-top') const switchBtn = document.querySelector('#changeimg') // 绑定按钮点击事件 switchBtn.addEventListener('click', function() { // 索引自增,超过最大值时重置为0实现循环切换 currentIndex = currentIndex >= maxIndex ? 0 : currentIndex + 1 // 替换图片src属性 targetImg.src = `/img/new${currentIndex}.JPG` }) </script>
可选调整说明
- 不需要循环切换:将索引自增逻辑替换为
if (currentIndex < maxIndex) currentIndex++即可,到new6.JPG后点击按钮不再切换 - 不需要包含初始的new0.JPG:将初始
currentIndex设为0,首次点击直接跳转到new1.JPG即可,逻辑无需额外修改
内容的提问来源于stack exchange,提问作者LEGENDRYzZzZ
相关产品推荐
相关产品推荐

