我试图让图像的大小在JavaScript中,使用这种代码:如何在html/javascript中使用dom检索图像的大小?
var image = document.createElement("img");
image.src = "http://home.cse.ust.hk/~rossiter/mooc/matching_game/smile.png";
然后我一直在尝试使用image.width
或image.naturalWidth
获取图像的宽度,但它检索0。
我试图让图像的大小在JavaScript中,使用这种代码:如何在html/javascript中使用dom检索图像的大小?
var image = document.createElement("img");
image.src = "http://home.cse.ust.hk/~rossiter/mooc/matching_game/smile.png";
然后我一直在尝试使用image.width
或image.naturalWidth
获取图像的宽度,但它检索0。
您已经创建使用上面的代码元素后。您可以使用
image.height
image.width
究其原因,你会得到0是因为当你执行该语句,它不会必须加载。您必须等待图像加载并执行语句。您可以使用document.ready
,但问题是它可能不是100%准确的。
参考:Official way to ask jQuery wait for all images to load before executing something
您可以使用window.load(使用jQuery),但是这是一些东西,是有风险的按照上面的文章。
对于最佳的解决方案,你可以使用什么LIB https://github.com/desandro/imagesloaded。
您可以使用@拉曼的技术,但问题是,你必须每幅图像可能让clumpsy事件侦听附加到。
如果您正在使用imagesloaded,你可以看的要加载图像的容器,并相应地执行代码。
的jsfiddle:https://jsfiddle.net/52q0juq6/1/
你需要对图像的load
计算图像尺寸。 Here是一个演示相同的小提琴。
image.addEventListener('load', function(){
console.log(image.width);
console.log(image.height);
});
它是因为图像尚未加载。
<html>
<img id="theImage" src="http://home.cse.ust.hk/~rossiter/mooc/matching_game/smile.png" />
<button id="Ok" value="Ok" onclick="ShowImageWidth()" />
<script type="text/JavaScript">
//This runs when the page loads and shows 0
var element = document.getElementById('theImage');
alert(element.width);
//This runs AFTER the page has loaded and the button is clicked and shows 100
function ShowImageWidth() {
var element = document.getElementById('theImage');
alert(element.width);
}
</script>
</html>
为什么要用一个额外的库来做这样简单的工作。 – Raman
只需要1张图片就可以了,你可以添加一个监听器。但是,如果你正在从事一个项目......我会认为它是生产就绪代码,处理多个图像/资产,然后它不是简单的权利!但是,如果这只是一个测试,那么eventlistener是不错的:)。 –
其生产就绪代码,如果要求得到一个单一图像的尺寸,那么你并不需要一个完全成熟的JS库,它的,这是什么问的问题。和BTW您的库还重视在后台的元素加载事件监听器,所以它不喜欢你节省'DOM'事件侦听器什么的 – Raman