2015-04-02 31 views
0

我想我的隱藏div顯示點擊的div的背景圖像作爲圖像src.How我可以改變我的代碼來實現這一目標嗎? 此致敬禮。
插入圖像使用另一個div的背景圖像使用JS

<div id="hidden_div"></div> 

<!-- JavaScript --> 
<script> 
function func(element) { 
var hidden = document.getElementById("hidden_div"); 
hidden.style.backgroundImage = element.style.backgroundImage; 
} 
</script> 
+0

我不明白的問題。你爲什麼要將背景設置爲隱藏的'div'? – 2015-04-02 17:37:33

回答

0

我想你想的<img>元素附加到你的隱藏DIV,對吧?

然後:

<!-- JavaScript --> 
<script type="text/javascript"> 
function func(element) { 
    var hidden = document.getElementById("hidden_div"); 
    // Create <img> element 
    var imgElement = document.createElement("IMG"); // creating 
    // backgroundImage contains url(path/to/image), we want to extract the quoted string 
imgElement.src=element.style.backgroundImage.replace('url(','').replace(')',''); 
hidden.appendChild(imgElement); 
} 
</script> 
0

對於非內嵌樣式,你可以用window.getComputedStyle閱讀:

function func(element) { 
    var hidden = document.getElementById("hidden_div"); 
    hidden.style.backgroundImage = window.getComputedStyle(document.getElementById(element), null).getPropertyValue("background-image"); 
}