从div获取背景图像src并将其设置为图像的src [英] Get background-image src from div and set that as an image's src

查看:195
本文介绍了从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;
}

继续摇摆!

这篇关于从div获取背景图像src并将其设置为图像的src的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆