Javascript 获取已调整大小图像的clientWidth和clientHeight
我正在根据当前视口大小调整JavaScript中图像的大小。没有媒体查询和其他类似的东西,JS一直存在,元素没有静态大小 所以基本上看起来是这样的:Javascript 获取已调整大小图像的clientWidth和clientHeight,javascript,jquery,google-closure-library,Javascript,Jquery,Google Closure Library,我正在根据当前视口大小调整JavaScript中图像的大小。没有媒体查询和其他类似的东西,JS一直存在,元素没有静态大小 所以基本上看起来是这样的: var computedHeight = viewport.height * someRatio; var image = goog.dom.createDom('img', { 'src': 'the.link.to.the.image', 'height': computedHeight + 'p
var computedHeight = viewport.height * someRatio;
var image = goog.dom.createDom('img', {
'src': 'the.link.to.the.image',
'height': computedHeight + 'px',
'width': 'auto'
};
显示图像后,请尝试查询以下属性
image.offsetWidth
image.offsetHeight
显示图像后,请尝试查询以下属性
image.offsetWidth
image.offsetHeight
试试goog.style.getComputedStyle(图像“宽度”)。您可能需要先将其添加到文档中。试试goog.style.getComputedStyle(图像“宽度”)。您可能需要先将其添加到文档中。正如其他人所说,在图像插入文档之前,您无法获得大小 但是你可以自己计算尺寸 加载图像后,您可以访问图像的原始大小。基于此,计算缩放尺寸并不十分困难:
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);
}
});
正如其他人所说,在将图像插入文档之前,无法获取大小 但是你可以自己计算尺寸 加载图像后,您可以访问图像的原始大小。基于此,计算缩放尺寸并不十分困难:
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);
}
});
查一查小提琴,这是你要找的吗?(调整窗格大小,以便更改大小并触发日志记录)如果在图像附加到主体并加载后使用offsetWidth和OffsetSight,它们应该工作检查小提琴,这是您要的吗?(调整窗格大小,以便更改大小并触发日志记录)如果在将图像附加到主体并加载后使用offsetWidth和OffsetSight,它们应该可以在视口中工作。
高度是问题所在吗?尝试document.body.clientHeight
Hmm<代码>视口。高度
似乎不是问题…:)<代码>视口。高度这里有问题吗?尝试document.body.clientHeight
Hmm<代码>视口。高度似乎不是问题…:)。