[英]Get real size of background image of div using JavaScript
所以,我想采用div的背景圖像的真實大小,並在網站上搜索我在這個網址中找到了一些很棒的JavaScript代碼: http : //jsbin.com/olozu/2/edit 。
但是,它似乎不適用於我的網站,雖然我的代碼與上面的相同,但我找不到原因。
這是我的代碼( JS Bin )
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body onclick="picture()">
<img id="topicinfo" src="http://pierre.chachatelier.fr/programmation/images/mozodojo-original-image.jpg"><
</body>
</html>
JavaScript的:
function picture()
{
var a=document.getElementById("topicinfo").height;
alert(a);
}
如果單擊左側的圖像,則顯示0寬度0高度。
您正嘗試從style
屬性獲取信息,但由於您沒有將圖像背景聲明為內聯,因此style
為null。 你必須得到計算的風格。 在這里看到這個主題; 最佳答案提供了全面的解釋。
另一個好資源:
編輯:更具體地說,你要做的是:
var imageUrl = getComputedStyle(document.getElementById('topicinfo'));
var imageSrc = imageUrl.replace(/"/g,"")
.replace(/url\(|\)$/ig, "");
我仍然建議查看這些資源,因為它們提供了一種很好的方法來實現一個函數,使這種動作很容易重復。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.