如何点击非图片列表项修改img src,实现文本触发的图片切换功能
实现方案
1. 调整HTML结构
补充上下切换按钮,同时修正原有HTML中li元素缺少父级ul的问题:
<div class="container" style="width: 700px;"> <div class="list"> <ul> <li>img1.jpg</li> <li>img2.jpg</li> <li>img3.gif</li> <li>img4.png</li> </ul> </div> <div class="show"> <button id="prevBtn" class="switch-btn">上一张</button> <img src="img1.jpg" class="display" id="display"> <button id="nextBtn" class="switch-btn">下一张</button> </div> </div>
2. 补充CSS样式
原有CSS保持不变,新增按钮、列表样式:
/* 原有CSS代码保持不变,新增以下内容 */ .list ul { margin: 0; padding: 0; list-style: none; } .list li { padding: 8px 12px; border-bottom: 1px solid #eee; cursor: pointer; } .show { position: relative; } .switch-btn { position: absolute; top: 50%; transform: translateY(-50%); z-index: 10; width: 60px; height: 36px; border: none; background-color: rgba(0,0,0,0.6); color: #fff; cursor: pointer; border-radius: 4px; } #prevBtn { left: 10px; } #nextBtn { right: 10px; } .switch-btn:hover { background-color: rgba(0,0,0,0.8); }
3. 原生JavaScript实现逻辑
无需引入任何第三方库,直接插入script标签即可运行:
// 初始化变量 let currentIndex = 0; const imgList = document.querySelectorAll('.list li'); const displayImg = document.getElementById('display'); const prevBtn = document.getElementById('prevBtn'); const nextBtn = document.getElementById('nextBtn'); // 绑定列表项点击事件 imgList.forEach((item, index) => { item.addEventListener('click', () => { currentIndex = index; updateImg(); }) }) // 绑定上一张按钮事件 prevBtn.addEventListener('click', () => { currentIndex = currentIndex === 0 ? imgList.length - 1 : currentIndex - 1; updateImg(); }) // 绑定下一张按钮事件 nextBtn.addEventListener('click', () => { currentIndex = currentIndex === imgList.length - 1 ? 0 : currentIndex + 1; updateImg(); }) // 统一更新图片和选中状态 function updateImg() { const imgPath = imgList[currentIndex].textContent.trim(); displayImg.src = imgPath; // 高亮当前选中的列表项,不需要可删除以下两行 imgList.forEach(item => item.style.backgroundColor = 'transparent'); imgList[currentIndex].style.backgroundColor = '#f0f0f0'; } // 初始化默认选中状态 updateImg();
可选:jQuery实现版本
如果项目已经引入jQuery,可使用以下简化版逻辑:
$(function() { let currentIndex = 0; const $imgList = $('.list li'); const $displayImg = $('#display'); $imgList.click(function() { currentIndex = $(this).index(); updateImg(); }) $('#prevBtn').click(() => { currentIndex = currentIndex === 0 ? $imgList.length - 1 : currentIndex - 1; updateImg(); }) $('#nextBtn').click(() => { currentIndex = currentIndex === $imgList.length - 1 ? 0 : currentIndex + 1; updateImg(); }) function updateImg() { const imgPath = $imgList.eq(currentIndex).text().trim(); $displayImg.attr('src', imgPath); $imgList.css('background-color', 'transparent').eq(currentIndex).css('background-color', '#f0f0f0'); } updateImg(); })
自定义修改提示
如果图片路径和列表文本不完全一致,比如图片统一存放在/images/目录下,只需修改updateImg方法中赋值src的逻辑,拼接对应路径前缀即可:displayImg.src = '/images/' + imgPath;
内容的提问来源于stack exchange,提问作者kherezae
相关产品推荐
相关产品推荐

