获取图像的原生宽度

Avatar of Chris Coyier
Chris Coyier on

如果你使用 jQuery 选择一个图像,然后使用 .width(),你将获得图像的当前宽度,即使它已经被缩放(例如 max-width: 100%;)。你可以通过以下方法访问图像的原生宽度(即使它没有任何声明其宽度的属性)

// Get on screen image
var screenImage = $("#image");

// Create new offscreen image to test
var theImage = new Image();
theImage.src = screenImage.attr("src");

// Get accurate measurements from that.
var imageWidth = theImage.width;
var imageHeight = theImage.height;