获取大小调整后的图片的clientWidth和clientHeight [英] Get the clientWidth and clientHeight of resized image

查看:358
本文介绍了获取大小调整后的图片的clientWidth和clientHeight的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在基于当前视口大小调整JavaScript中图像的大小.没有媒体查询和其他类似的东西,一直都是JS,也没有元素的静态大小.

I am resizing an image in JavaScript based on the current viewport size. No media queries and other such things, JS all the way, and no static sizes for elements.

所以基本上看起来像这样:

So basically it looks something like this:

    var computedHeight = viewport.height * someRatio;
    var image = goog.dom.createDom('img', {
        'src': 'the.link.to.the.image',
        'height': computedHeight + 'px',
        'width': 'auto'
    };

推荐答案

正如其他人所说,在将图像插入文档之前,您无法获得大小.

As the others said, you can't get the size before the image has been inserted into the document.

但是您可以自行计算大小.

But you can calculate the size on your own.

加载图像后,您可以访问图像的原始尺寸.基于此,计算缩放的大小并不是很困难:

When the image has been loaded, you may access the original size of the image. Based on this it's not very difficult to calculate the scaled size:

    var image = goog.dom.createDom('img', {
    'src': 'the.link.to.the.image',
    'height': computedHeight + 'px',
    'width': 'auto',
    'onload':function(){
      alert('width:'+
            Math.floor((this.naturalWidth*this.height)/this.naturalHeight)+
            '\nheight:'+this.height);        
    }
});

这篇关于获取大小调整后的图片的clientWidth和clientHeight的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆