是否有JavaScript或jQuery API或方法来获取页面上图像的尺寸?


当前回答

你还可以使用:

var image=document.getElementById("imageID");
var width=image.offsetWidth;
var height=image.offsetHeight;

其他回答

你还可以使用:

var image=document.getElementById("imageID");
var width=image.offsetWidth;
var height=image.offsetHeight;

用jQuery库-

使用.width()和.height()。

更多jQuery宽度和jQuery高度。

示例代码:

$(文档)时函数(){ $("按钮”).click(函数() { alert(”图像的宽度 : " + $("# img_exmpl”).width ()); alert("形象的高度 : " + $("# img_exmpl”).height ()); }); }); < script src = " https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js " > < /脚本> <img id="img_exmpl" src="http://images.all-free-download.com/images/graphicthumb/beauty_of_nature_9_210287.jpg"> <button> img显示尺寸</button>

要得到自然的高度和宽度:

.naturalHeight document.querySelector (img); .naturalWidth document.querySelector (img); < img src = " img.png " >

如果你想获取样式的高度和宽度:

document.querySelector(“img”).offsetHeight; document.querySelector(“img”).offsetWidth;

Try

函数大小(){ console.log(“宽度:${照片。宽度},高度:$ {pic.height}’); } <img id="pic" src="https://picsum.photos/300/150"> <按钮onclick = "尺寸()“>显示> < /按钮大小

其他所有人都忘记了的事情是,你不能在加载前检查图像大小。当作者检查所有发布的方法时,它可能只在本地主机上工作。

由于这里可以使用jQuery,请记住'ready'事件是在图像加载之前触发的。$('#xxx').width()和.height()应该在onload事件或以后触发。