得到的背景图像的URL和与URL创建新的img标签
问题描述:
<div class="data">
<img src="#" style="background:url('o.jpg')">
</div>
我想借此(背景)网址,并用SRC =“背景图像网址”创建新的img标签在相同的股利和使用JS或JQ删除旧img标签
我试图做到这一点from
var img = document.querySelector('img'),
// parse image URL and strip away url('')
imgURL = img.style.backgroundImage.replace('url("','').replace('")','');
img.src = imgURL;
// remove style attribute afterwards.
img.removeAttribute('style');
但它不是为我工作,所以我必须做它的其他方式
答
尝试这一个
var img = $('#img').css('background-image');;
\t
\t imgURL = img.replace('url("','').replace('")','');
\t img = imgURL;
\t
\t $('.data').html('<img src='+img+' width="100" height="100">'); \t
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="data">
<img src="#" style="background:url('o.jpg')" width="100" height="100" id="img">
</div>
+0
https://i.gyazo.com/2e55ffde37cb8b12e5afa26fd940f24b.png 得到这个错误 –
+0
它在我的设备上工作我认为你的代码找不到图像 – Bhargav
答
尝试以下代码: -
var img = document.querySelector('img');
\t // Get the background image style
\t var style = img.currentStyle || window.getComputedStyle(img, false);
\t var bi = style.backgroundImage.slice(4, -1);
\t
// create a new image
\t var newImage = document.createElement("IMG");
\t // Replace string double quotes
\t newImage.src = bi.replace(/^"|"$/g, '');;
// append image inside div to current image as it next sibling
img.parentNode.insertBefore(newImage, img.nextSibling);
// Remove old image
\t img.parentNode.removeChild(img);
<div class="data">
<img src="#" style="width:300px;height:250px;background-image: url('http://i.stack.imgur.com/5eiS4.png')"/>
</div>
答
与高度和宽度属性http://jsfiddle.net/z2jKA/564/
删除高度和宽度属性 http://jsfiddle.net/z2jKA/565/
我更改变化不大,在你的编码和其工作得非常好。你检查这个链接jsFiddle。我是通过修改代码来完成的。也许它对你很有帮助
$(function() {
var img = $('#img').css('background-image');;
imgURL = img.replace('url("','').replace('")','');
img = imgURL;
alert(img);
$("#img").attr("src",""+img+"").removeAttr('width').removeAttr('height');
});
你想做什么?获取网址图片并尝试使用此图片创建一个新图片,如背景图片?你可以访问src图像来改变图像..像$('#newImage')。attr({src:'YOUR-NEW-URL'}); – Roy
重复 - https://stackoverflow.com/questions/14013131/javascript-get-background-image-url-of-div – Sagar
是的,我可以使用jquery @manish yadav –