2014-02-09 50 views
3

爲什麼下面的代碼爲style.backgroundImage輸出一個空字符串?我如何檢索圖像的高度和寬度,以便我可以適當地設置div的尺寸?爲什麼elem.style.backgroundImage返回空而不是CSS屬性?

<!DOCTYPE html> 
<html> 
<head> 
    <link href="test.css" rel="stylesheet" type="text/css" /> 
</head> 
<body> 
    <div class="myDiv" onclick="outputBGImageUrl(this)"> 
     Click To Get BG Image Property 
    </div> 
    <script type="text/javascript"> 
     function outputBGImageUrl(elem){ 
      var bgImage = elem.style.backgroundImage; 
      console.log(bgImage); 
     } 
    </script> 
</body> 
</html> 

CSS:

.myDiv{ 
    background-image:url(box.jpg); 
} 
+2

'elem.style'是指在元素上設置的內嵌樣式。 – Bill

回答

4

elem.style指元素上設置的內嵌樣式之間。

正確的方式來獲得背景圖像可以在這裏找到:Javascript: Get background-image URL of <div>

這無論如何(有改良的網址,讓;-))。

var img = document.getElementById('your_div_id'), 
style = img.currentStyle || window.getComputedStyle(img, false), 
bg_image_url = style.backgroundImage.replace(/url\((['"])?(.*?)\1\)/gi, '$2').split(',')[0]; 

這裏是你將如何得到尺寸:

var image = new Image(); 

image.onload = function(){ 
    var width = image.width, 
    height = image.height; 
} 

image.src = bg_image_url; //set the src after you have defined the onload callback 
+0

建議鏈接到評論中的答案,而不是複製它。 – sachinjain024

+0

*可能*重複..他的問題是'爲什麼elem.style.backgroundImage返回空'。 – Bill

+0

謝謝。爲什麼在元素上設置的內聯樣式中包含CSS屬性? – theGuardian

0

它返回空的,因爲background-image樣式應該是括號""''

.myDiv{ 
background-image:url("box.jpg"); 
} 
+0

加入引號並沒有改變任何東西。您所引用的鏈接網頁也不起作用。問題是style.backgroundImage返回空而不是「url(box.jpg)」。他使用同樣的方法。比利馬修斯回答工作 – theGuardian

+0

@xyzk,報價是可選的;) – Bill

相關問題