点击含背景图的Div在Lightbox显示图片时出现undefined问题求助
解决点击Div获取背景图并在Lightbox中显示的问题
我来帮你搞定这个问题!你遇到的核心bug是对getComputedStyle返回值的理解偏差——它拿到的background-image是一个字符串,不是DOM图像元素,所以根本不存在.src属性,直接赋值自然会得到undefined。
问题拆解
当你执行window.getComputedStyle(this, null).getPropertyValue("background-image")时,得到的结果格式通常是这两种之一:
- 带引号:
url("../images/01.jpg") - 不带引号:
url(../images/01.jpg)
我们需要把这个字符串里的url(、)以及可能存在的引号剥离,才能拿到真正可用的图片URL。
修改后的完整代码
<div id="lightbox"> <span class="closeBTN">×</span> <img class="lbContent" src=""> </div> <div class="imgCon"> </div>
.imgCon { height: 500px; width: 15%; min-width: 200px; background-image: url(../images/01.jpg); background-position: center; background-size: auto 500px; margin-bottom: 66px; cursor: pointer; /* 加上这个让点击区域更直观 */ } #lightbox { display: none; /* 默认隐藏lightbox */ position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.8); display: flex; align-items: center; justify-content: center; } .lbContent { max-width: 90%; max-height: 90%; } .closeBTN { position: absolute; top: 20px; right: 30px; color: white; font-size: 40px; cursor: pointer; }
var lightbox = document.querySelector('#lightbox') img = document.querySelector('.imgCon') span = document.querySelector('.closeBTN') lbImg = document.querySelector('.lbContent') img.onclick = function(){ lightbox.style.display = "flex"; // 获取背景图的原始字符串 var galImgStr = window.getComputedStyle(this, null).getPropertyValue("background-image"); // 剥离url()包裹和引号,提取纯净URL var imgUrl = galImgStr.replace(/^url\(["']?/, '').replace(/["']?\)$/, ''); // 赋值给lightbox图片的src属性 lbImg.src = imgUrl; } span.onclick = function(){ lightbox.style.display = "none"; };
关键代码解释
replace(/^url\(["']?/, ''):匹配字符串开头的url(,以及可能存在的单/双引号,将其替换为空replace(/["']?\)$/, ''):匹配字符串结尾的),以及可能存在的单/双引号,将其替换为空
经过这两步处理后,就能得到直接可用的图片URL,赋值给lightbox里的图片就能正常显示了。
内容的提问来源于stack exchange,提问作者Hfee
相关产品推荐
相关产品推荐

