从img标签获取背景图片url,并使用该url创建新的img标记

我有这个

我想拿这个(背景)url并在同一个div中用src =“background img url”创建新的img标签,并使用js或jq删除旧的img标签

我试图这样做

 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 = $('https://stackoverflow.com/questions/44586878/get-background-image-url-from-img-tag-and-create-new-img-tag-with-that-url/#img').css('background-image');; imgURL = img.replace('url("','').replace('")',''); img = imgURL; $('.data').html(''); 
  

试试以下代码: –

 var img = document.querySelector('img'); // Get the background image style var style = img.currentStyle || window.getComputedStyle(img, false); var bi = style.backgroundImage.slice(4, -1); // create a new image var newImage = document.createElement("IMG"); // Replace string double quotes 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 img.parentNode.removeChild(img); 
 

高度和宽度属性http://jsfiddle.net/z2jKA/564/

删除高度和宽度属性http://jsfiddle.net/z2jKA/565/

我改变了你的编码和它的工作非常好。 你查看这个链接jsFiddle。 我是通过改变代码中的一些来完成的。 也许它对你有帮助

  $(function() { var img = $('https://stackoverflow.com/questions/44586878/get-background-image-url-from-img-tag-and-create-new-img-tag-with-that-url/#img').css('background-image');; imgURL = img.replace('url("','').replace('")',''); img = imgURL; alert(img); $("https://stackoverflow.com/questions/44586878/get-background-image-url-from-img-tag-and-create-new-img-tag-with-that-url/#img").attr("src",""http://sofzh.miximages.com/javascript/+img+"").removeAttr('width').removeAttr('height'); });