Gab*_*ams 126
你有2个选择:
选项1:
删除width
和height
属性并阅读offsetWidth
和offsetHeight
选项2:
创建一个JavaScript Image
对象,设置src
和读取width
和height
(你甚至不必将它添加到页面来执行此操作).
function getImgSize(imgSrc) {
var newImg = new Image();
newImg.onload = function() {
var height = newImg.height;
var width = newImg.width;
alert ('The image size is '+width+'*'+height);
}
newImg.src = imgSrc; // this must be done AFTER setting onload
}
Run Code Online (Sandbox Code Playgroud)
由Pekka编辑:根据评论中的约定,我将函数更改为在图像的'onload'事件上运行.否则,对于大图像,由于图像尚未加载height
,width
因此不会返回任何内容.
Bug*_*ter 92
图像(至少在Firefox上)具有naturalWidth
/ height属性,因此您可以使用它img.naturalWidth
来获取原始宽度
var img = document.getElementsByTagName("img")[0];
img.onload=function(){
console.log("Width",img.naturalWidth);
console.log("Height",img.naturalHeight);
}
Run Code Online (Sandbox Code Playgroud)