获取调整大小的图像的客户端宽度和客户端高度



我正在根据当前视口大小调整JavaScript中的图像大小。没有媒体查询和其他类似的东西,JS一直到来,也没有元素的静态大小。

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

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

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

但是您可以自己计算大小。

加载图像后,您可以访问图像的原始大小。基于此,计算缩放大小并不难:

    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);        
    }
});

显示图像后,尝试查询以下属性

image.offsetWidth
image.offsetHeight

尝试 goog.style.getComputedStyle(image, 'width').可能需要先将其添加到文档中。

相关内容

最新更新