javascript 无法工作,因为来自其他页面的变量为空(TypeError)

javascript wont work because variable from other page is null (TypeError)

  1. 此功能适用于第 1 页
  2. 控制台显示 TypeError: lightbox (from function below) is null
  3. 灯箱在第 2 页

    function setBackgroundImg() {
        var windowHeight = window.innerHeight;
        var bgImg = document.getElementById("kr-home-bg");
        var x = windowHeight + "px";
        bgImg.setAttribute("style","height:" + x); // line in question when page2 loads 
    }
    setBackgroundImg();
    window.addEventListener("resize", setBackgroundImg);
    
  4. 当上面的函数被注释掉时,下面的代码适用于 page2

  5. 未注释时:TypeError:bgImg(来自上面的函数)为空且不起作用
  6. bgImg 在第 2 页

    var lightbox = document.getElementById("lightbox");
    lightbox.style.display = "none"; //line in question when page1 loads
    var lightboxMaker = document.getElementById("enable-lightbox");
    var closeBu = document.getElementById("close-lightbox");
    var lightbox = document.getElementById("lightbox");
    function closeLightbox() {
        lightbox.style.display = "none";
    }
    closeBu.onclick = closeLightbox;
    
    lightboxMaker.onclick = function() {
        lightbox.style.display = "block";
    };
    
当您 运行 setBackgroundImg() 时,

document.getElementById("kr-home-bg") 必须在 DOM 中可用。这样做的原因 onresize 是因为元素当时确实存在。如果 JavaScript 动态创建您的 HTML 它必须先于您 运行 setBackgroundImg() 在第一页上发生。

在我看来你可以只用 CSS 解决这个问题,因为 document.getElementById("kr-home-bg") 占据了整个 window:

#kr-home-bg{
  background: url('yourImage.png'); background-size:100%;
}

如果您设置了宽度,只需在 100% 之前加上 space。