欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

JavaScript获取图片(Image)的大小(宽度,高度)

程序员文章站 2022-04-01 11:58:49
...
如果只有图片的URL
function getImageDimensions(imgStyleRule) {
  var defaultSize, img;
  defaultSize = {
    width: 10,
    height: 30
  };
  if (!imgStyleRule || !imgStyleRule.style || !imgStyleRule.style.backgroundImage) {
    return defaultSize;
  }
  img = new Image();
  img.src = imgStyleRule.style.backgroundImage.replace(/url\(|\)$|"/ig, '');
  return {
    width: img.width,
    height: img.height
  };
}


[size=medium]
如何获取imgStyleRule, 参考
http://darrenzhu.iteye.com/admin/blogs/2065946


如果图片已经加载,可以通过如下方式获取
var img = document.getElementById('imageid'); 
//or however you get a handle to the IMG
var width = img.clientWidth;
var height = img.clientHeight;

[/size]