从div获取背景图像src并将其设置为图像的src
因此,我试图在单击div时从div抓取背景图像,并将其设置为页面上其他位置的img元素的src.问题是我收到一条错误消息,指出未找到该文件.我知道这与我分配给img的src的路径有关,但是我看不到代码出了什么问题.
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.
单击所涉及的div时,它将调用一个函数
When the div in question is clicked it calls a function
document.getElementById('rice-bowl').onclick=openModal;
下面是实际功能
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!
这应该是:
$("#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;
}
继续摇摆!