JS获取背景图像,然后在灯箱中显示

时间:2018-01-07 03:45:27

标签: javascript

我有一组带有背景图片的 divs 。我试图获取图像onclick然后将其显示在灯箱中。当灯箱弹出时,我得到的图像未定义。我可以通过控制台正确显示图片 url 。我知道lbImg.src = galImg.src;不正确,但我不确定如何解决它。

HTML

<div id="lightbox">
    <span class="closeBTN">&times;</span>

    <img class="lbContent" src="">
 </div>

<div class="imgCon">

</div>

CSS

.imgCon
{
 height: 500px;
 width: 15%;
 min-width: 200px;
 background-image: url(../images/01.jpg);
 background-position: center;
 background-size: auto 500px;
 margin-bottom: 66px;
}

JS

var lightbox = document.querySelector('#lightbox')
    img = document.querySelector('.imgCon')
    span = document.querySelector('.closeBTN')
    lbImg = document.querySelector('.lbContent')

img.onclick = (function(){
    lightbox.style.display = "block";
    var galImg = window.getComputedStyle(this, 
    null).getPropertyValue("background-Image");
    lbImg.src = galImg.src;
    //console.log(galImg);
})

span.onclick = (function(){
    lightbox.style.display = "none";

}); 

2 个答案:

答案 0 :(得分:0)

请你试试lbImg.setAttribute('src', galImg.src)

答案 1 :(得分:0)

您在 // Creates a button var mainButton = document.createElement("button"); mainButton.style.width = "10%"; // Get the Screens Avaliable Width and Get 10% of it and convert it to pixels var wad = screen.availWidth * .1 + "px"; // Thinking this would return the pixel amount the circle button is, but it only works on the regular screen and not when resized. It also does not work for mobile. console.log(wad); mainButton.style.height = wad; 中获得了背景图像本身,因此您需要直接设置它(它是一个字符串,并且没有galImg属性)。

但是,我们从getComputedStyle获得的galImg值是一个类似于:.src的字符串。我们必须从中移除"url("file:.../Desktop/1.png")"部分以及引号(&#34; ...&#34;):

url(