在javascript中设置vars中图像的高度和宽度

时间:2016-03-03 11:06:50

标签: javascript html

我尝试将图片作为背景并符合浏览器的尺寸。但是,我得到:expmrt.html:15 Uncaught TypeError: Cannot set property 'width' of null



//Get the browser legth and height, then after the code is done, time out in 300 miliseconds.
function ScreenLoop() {
  var Width = window.innerWidth;
  var Height = window.innerHeight;
  alert("Width: " + Width + " and also Height: " + Height) //Debugging reasons
  document.getElementById("theimage").width = Width; // Where the error: expmrt.html:15 Uncaught TypeError: Cannot set property 'width' of null) occures for some reason.
  document.getElementById("theimage").height = Height;
  setTimeout(ScreenLoop(), 300);
};
ScreenLoop();

<img src="tl2fZkc.png" id="theimage" width="50" height="50" alt="theimage" />
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

从窗口

中调用load事件中的ScreenLoop()
window.onload = function() {
   ScreenLoop();
}