naturalWidth与naturalHeight获取图片原始大小

    naturalWidth与naturalHeight属性是在html5权威指南上发现的,这二者属性获得的是图片原始的尺寸不会因外部width和height属性设置的改变而改变

示例如下:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<body>
		<img id="image" src="2.png" style="display:block;" width="100" height="100" />
		<script>
			window.onload = function(){
				var image = document.getElementById("image");
				console.log("原始宽度:"+image.naturalWidth);
				console.log("原始高度:"+image.naturalHeight);
				console.log("宽:"+image.width);
				console.log("高:"+image.height);
			}
		</script>
	</body>
</html>

运行结果:

我们可以看到,这个原始宽高,不受设置的影响。

需要注意的是:

图片必须提前加载,否则,图片原始宽高均为0,如下图



发布了12 篇原创文章 · 获赞 7 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/a18792627168/article/details/79964258