[英]Get background-image src from div and set that as an image's 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. 因此,我试图在单击div时从div抓取背景图像,并将其设置为页面上其他位置的img元素的src。 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. 我知道这与我分配给img的src的路径有关,但是我看不到代码出了什么问题。
When the div in question is clicked it calls a function 单击有问题的div时,它将调用一个函数
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! 再次,任何帮助将不胜感激!
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! 继续摇摆!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.