2017-06-16 51 views
0

我有這個得到的背景圖像的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'); 

但它不是爲我工作,所以我必須做它的其他方式

+0

你想做什麼?獲取網址圖片並嘗試使用此圖片創建一個新圖片,如背景圖片?你可以訪問src圖像來改變圖像..像$('#newImage')。attr({src:'YOUR-NEW-URL'}); – Roy

+0

重複 - https://stackoverflow.com/questions/14013131/javascript-get-background-image-url-of-div – Sagar

+0

是的,我可以使用jquery @manish yadav –

回答

1

嘗試這一個

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

2

嘗試以下代碼: -

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>

0

與高度和寬度屬性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'); 


});