【问题标题】:Get the clientWidth and clientHeight of resized image获取调整后图片的clientWidth和clientHeight
【发布时间】:2012-11-14 19:13:23
【问题描述】:

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

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

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

【问题讨论】:

  • viewport.height 是这里的问题吗?试试document.body.clientHeight
  • 嗯...viewport.height 似乎不是问题... :)。

标签: javascript jquery google-closure-library


【解决方案1】:

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

但您可以自行计算大小。

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

    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】:

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

    image.offsetWidth
    image.offsetHeight
    

    【讨论】:

    • 检查小提琴,这是你所追求的吗? jsfiddle.net/KLfau/5(调整窗格大小以更改大小并触发日志记录)
    • 如果在图像被附加到正文并加载后使用 offsetWidth 和 offsetHeight,它们应该可以工作
    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 2012-07-30
      • 2015-12-03
      • 2013-04-20
      • 2019-09-17
      • 2020-01-30
      • 2021-02-21
      • 2020-03-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多