Get the clientWidth and clientHeight of resized image

偶尔善良 提交于 2019-12-25 09:48:15

问题


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

回答1:


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



回答2:


After the image has been displayed try querying the following properties

image.offsetWidth
image.offsetHeight



回答3:


Try goog.style.getComputedStyle(image, 'width'). Probably you'll need to add it to the document first.



来源:https://stackoverflow.com/questions/13385657/get-the-clientwidth-and-clientheight-of-resized-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!