Javascript 获得真实的图像宽度和高度
当我使用Javascript 获得真实的图像宽度和高度,javascript,Javascript,当我使用image.width时,它返回屏幕上显示的图像宽度,我在图像上使用max width属性,该图像显示在一些div中。真实图像的大小要大得多。有可能获得真实图像的宽度吗?您需要在图像的onload事件中访问它 JS var testImg = document.getElementById('testImg'), iWidth=document.getElementById('width'), iHeight = document.getElementById
image.width
时,它返回屏幕上显示的图像宽度,我在图像上使用max width
属性,该图像显示在一些div
中。真实图像的大小要大得多。有可能获得真实图像的宽度吗?您需要在图像的onload事件中访问它
JS
var testImg = document.getElementById('testImg'),
iWidth=document.getElementById('width'),
iHeight = document.getElementById('height');
testImg.onload = function(){
console.log(this);
iWidth.value=this.width;
iHeight.value=this.height;
};
这里是它的JSFIDLE:您可以通过创建一个具有相同源的新图像来获得图像的真实尺寸,并获得该图像的尺寸
var img = new Image();
img.onload = function() {
var w = this.width,
h = this.height;
}
img.src = $('img')[0].src; // or whatever
首先,要知道图像是异步加载的,这意味着您必须编写代码,以便在回调函数中获得结果。然后,使用没有显式样式的新图像对象(这样它可以调整大小以适应本机图像尺寸)触发回调。例如:
function whatWidth(url, onSize) {
var img = new Image();
img.src = url;
img.onload = function() {
onSize(img.width, img.height);
}
}
// Now get the dimensions of an image ...
whatWidth('http://icons.iconarchive.com/icons/deleket/keriyo-emoticons/256/Smiley-rofl-icon.png',
function(w, h) {
console.log('width x height: ', w, h);
}
);
// => Outputs "width x height: 256 256"
值得注意的是,虽然这可能需要向服务器请求获取图像(与网页上实际显示的图像对象无关),但只要url与网页上的图像相同,浏览器缓存就会[通常]确保只发出一个请求。以缓存为例,以备需要(我知道最初的问题提到了JS,但逻辑保持不变):
class\u图标化{
最终整型宽度;
最终整数高度;
_IconSize(这个.宽度,这个.高度);
}
I类装载机{
静态最终IconLoader_this=新IconLoader._init();
工厂IconLoader()=>\u此;
//Url->维度。
最终映射_cache={};
IconLoader._init(){}
带大小的void(字符串url,已加载的void(int-width,int-height)){
if(_cache.containsKey(url)){
已加载(_缓存[url]。宽度,_缓存[url]。高度);
}否则{
最终ImageElement img=新ImageElement();
img.onLoad.listen((){
var iconSize=新的iconSize(img.宽度,img.高度);
_缓存[url]=iconSize;
withSize(url,已加载);
});
img.src=url;
}
}
}
结果是有一个自然宽度
属性 您是如何获得图像的?它是一个JS图像对象还是一个DOM元素?你能把一个简单的代码示例放在一起吗?因为这和OP遇到的问题是一样的。它得到的是DOM元素的宽度,而不是原始图像的宽度。这里有一个例子:有理由不使用吗?@siikamiika-不,这些也很好,我怀疑我在五年前写这篇文章时没有使用它们,因为width
和height
有更好的支持吗?@adeneo我知道,根据IE6到IE8,我不支持它
class _IconSize {
final int width;
final int height;
_IconSize(this.width, this.height);
}
class IconLoader {
static final IconLoader _this = new IconLoader._init();
factory IconLoader() => _this;
// Url -> dimensions.
final Map<String, _IconSize> _cache = {};
IconLoader._init() {}
void withSize(String url, void onLoaded(int width, int height)) {
if (_cache.containsKey(url)) {
onLoaded(_cache[url].width, _cache[url].height);
} else {
final ImageElement img = new ImageElement();
img.onLoad.listen((_) {
var iconSize = new _IconSize(img.width, img.height);
_cache[url] = iconSize;
withSize(url, onLoaded);
});
img.src = url;
}
}
}