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

Setting height, and width of an image from vars in javascript

本文关键字:高度 图像 javascript 设置 变量      更新时间:2023-09-26

我正在尝试制作一个图像作为背景并适合浏览器的尺寸。但是,我得到: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" />

从窗口调用加载事件中的 ScreenLoop()

window.onload = function() {
   ScreenLoop();
}