简体   繁体   English

从div获取背景图像src并将其设置为图像的src

[英]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.

相关问题 如何使用jQuery选择器,获取图像的src并将其设置为另一个元素的背景图像? - How to jQuery selectors, get an image's src and set it as a background-image of another element? Javascript得到错误的背景图像SRC - Javascript get wrong background-image src jQuery - src 和背景图像的图像上传器 - jQuery - Image Uploader for src and background-image 如何获取div的背景图像值并将其应用于img标签onclick的src值? - How can I get the background-image value of a div and apply it to the src value of an img tag onclick? 用div的data属性将包含特定字符串的匹配图像的src替换为css background-image - Replace matching image's src containing specific string with div's data attribute onto css background-image &lt;img src&gt;作为div中的背景图像 - < img src> as background image in div 使img元素的src成为另一个元素的背景图像 - Making an img element's src another element's background-image 无法绘制由“内容”或“背景图像”而不是“ src”指定的图像 - Cannot drawImage specified by “content” or “background-image” rather than “src” 将aspx文件放在背景图像中,例如im src - Put aspx file in background-image like im src 从现有的获取背景图片网址 <div> 和/或向背景图片添加其他属性 - Get the background-image url from an existing <div> and/or add another attribute to background-image
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM