因此,我想获取div的背景图片的真实大小,并在该站点中进行搜索,发现该URL中有一些很棒的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。您必须获取计算出的样式。在这里看到这个线程;最佳答案提供了全面的解释。
Read CSS property of an element using JavaScript
另一个好的资源:
http://javascript.info/tutorial/styles-and-classes-getcomputedstyle#getcomputedstyle-and-currentstyle
编辑:更具体地说,您要做的是:
var imageUrl = getComputedStyle(document.getElementById('topicinfo'));
var imageSrc = imageUrl.replace(/"/g,"")
.replace(/url\(|\)$/ig, "");
但我仍然建议您查看这些资源,因为它们提供了一种很好的方式来实现使这种 Action 易于重复的功能。