Get background-image src from div and set that as

2019-09-14 07:03发布

So I'm trying to grab the background-image from a div when it is clicked and set it as the src of an img element somewhere else on the page. The issue is that I'm getting an error saying that the file is not found. I understand that this has something to do with the path that I'm assigning to the img's src, however I am unable to see what's wrong with the code.

When the div in question is clicked it calls a function

document.getElementById('rice-bowl').onclick=openModal; 

And below is the actual function

var openModal=function(){
        var image= $(this).css('background-image').slice(4,-1);
        console.log(image);
        var modalImg = document.getElementById("img01");
        modalImg.src = image;
        console.log(modalImg.src);
    }

The two outputs to console should be the same according to this logic however, they are not. Again, any help would be greatly appreciated!

1条回答
forever°为你锁心
2楼-- · 2019-09-14 08:00

this should be:

$("#rice-bowl").click(function() {
    var bg = $(this).css('background-image');
    bg = bg.replace('url(','').replace(')','').replace(/\"/gi, "");
    var modalImg = document.getElementById("img01");
    modalImg.src = bg;
}

Keep rocking!

查看更多
登录 后发表回答