JavaScript:使用getComputedStyle()获取图像的大小

JavaScript: getting the size of an image using getComputedStyle()

本文关键字:图像 获取 使用 getComputedStyle JavaScript      更新时间:2024-04-03

我目前遇到一个"奇怪的问题"。。。我是JavaScript的初学者,我想获得图像的高度来设置图像的大小。

  1. 我得到屏幕的宽度
  2. 我设置了取决于屏幕大小的图像宽度=>我想电脑也设置了图像的高度
  3. 我问图像的高度
  4. 我打印它

这是代码:

var screenWidth = (window.innerWidth);  
myImg.width = Math.floor(screenWidth/3); // That works, my image is sized well.  
var imgLarg = getComputedStyle(myImg,null).height.toLowerCase()  
console.log(imgLarg); 

问题如下:当我通过网址重新加载页面来刷新页面时,它是有效的。但是,当我按下刷新按钮时,代码返回"0px"。

将代码封装在document.ready中(如果使用jquery)或侦听DOMContentLoaded。等待图像完全加载后再获取其尺寸。如果使用jquery或Image.onload(),请使用.load

http://api.jquery.com/ready/
http://api.jquery.com/load/
http://developer.mozilla.org/En/XUL/Attribute/Onload