javascript无法工作,因为来自其他页面的变量为null(TypeError) 此功能在第1页起作用 控制台显示TypeError:lightbox(来自下面的函数)为空
灯箱在第二页javascript无法工作,因为来自其他页面的变量为null(TypeError) 此功能在第1页起作用 控制台显示TypeError:lightbox(来自下面的函数)为空,javascript,typeerror,Javascript,Typeerror,灯箱在第二页 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 load
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);
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";
};
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);
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()
时,必须在DOM中提供document.getElementById(“kr home bg”)
。之所以这样做是因为元素当时确实存在。如果JavaScript动态创建HTML,则必须在第一页上运行setBackgroundImg()
之前执行
在我看来,您只需要CSS就可以解决这个问题,因为document.getElementById(“kr home bg”)
占据了整个窗口:
#kr-home-bg{
background: url('yourImage.png'); background-size:100%;
}
如果设置了宽度,只需在
100%
7之前加上空格即可。如果getElementById
找不到元素,或者因为它根本不在源代码中,或者因为它在DOM中加载元素之前运行,则加载新页面时,它返回null
,并以所有新变量开始。在一页中设置的变量不会传递到下一页。如果您想要持久数据,请使用Cookie或本地存储。感谢您的帮助。现在,我为另一个页面创建了另一个脚本文件。是的,随着我不断的学习,我会想写得更有效率。谢谢你给我额外的小费。