Get background-image src from div and set that as an image's src

旧城冷巷雨未停 提交于 2019-12-12 02:24:43

问题


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:


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!



来源:https://stackoverflow.com/questions/43175307/get-background-image-src-from-div-and-set-that-as-an-images-src

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!