是否有JavaScript或jQuery API或方法来获取页面上图像的尺寸?
当前回答
使用jQuery,你可以这样做:
var imgWidth = $("#imgIDWhatever").width();
其他回答
你只能使用load事件的回调来做到这一点,因为图像的大小直到它实际完成加载才知道。类似于下面的代码……
var imgTesting = new Image();
function CreateDelegate(contextObject, delegateMethod)
{
return function()
{
return delegateMethod.apply(contextObject, arguments);
}
}
function imgTesting_onload()
{
alert(this.width + " by " + this.height);
}
imgTesting.onload = CreateDelegate(imgTesting, imgTesting_onload);
imgTesting.src = 'yourimage.jpg';
Try
函数大小(){ console.log(“宽度:${照片。宽度},高度:$ {pic.height}’); } <img id="pic" src="https://picsum.photos/300/150"> <按钮onclick = "尺寸()“>显示> < /按钮大小
在获取元素的属性之前,文档页面应该是onload的:
window.onload = function(){
console.log(img.offsetWidth,img.offsetHeight);
}
你还可以使用:
var image=document.getElementById("imageID");
var width=image.offsetWidth;
var height=image.offsetHeight;
要得到自然的高度和宽度:
.naturalHeight document.querySelector (img); .naturalWidth document.querySelector (img); < img src = " img.png " >
如果你想获取样式的高度和宽度:
document.querySelector(“img”).offsetHeight; document.querySelector(“img”).offsetWidth;