如何通过JavaScript实现点击缩略图在模态框中加载对应大图
实现点击缩略图加载对应大图的模态框方案
你只需要调整原有代码中点击事件的图片路径生成逻辑即可,以下是修改完成的完整可运行代码:
// Get the modal var modal = document.getElementById('myModal'); // Get the image and insert it inside the modal - use its "alt" text as a caption var img = $('.myImg'); var modalImg = $("#img01"); var captionText = document.getElementById("caption"); $('.myImg').click(function(){ modal.style.display = "block"; // 核心修改:去除文件名中的_thumb后缀得到大图路径 var newSrc = this.src.replace(/_thumb(\.\w+)$/, '$1'); modalImg.attr('src', newSrc); captionText.innerHTML = this.alt; }); // Get the <span> element that closes the modal var span = document.getElementsByClassName("close")[0]; // When the user clicks on <span> (x), close the modal span.onclick = function() { modal.style.display = "none"; } // 额外优化:点击模态框背景也可关闭 modal.onclick = function(e) { if(e.target === modal) { modal.style.display = "none"; } }
修改说明
- 核心改动点是用
replace方法结合正则表达式,匹配文件名末尾的_thumb字符并删除,得到对应大图的路径 - 正则
/_thumb(\.\w+)$/只会匹配位于扩展名前的_thumb后缀,不会误修改图片路径其他位置出现的_thumb字符,适用场景更广 - 如果你的图片路径中不会在其他位置出现
_thumb,也可以用更简单的写法:var newSrc = this.src.replace('_thumb.', '.');,效果完全一致
内容的提问来源于stack exchange,提问作者Jenny Forest
相关产品推荐
相关产品推荐

