我有一个可以动态定位背景图像的 JavaScript 函数:
window.onload = function() {
bw = document.getElementsByClassName("BottomWrapper");
if (bw.length===0){
bw = document.getElementsByClassName("BottomWrapper2");
}
pos = window.innerWidth/2 - 490.5;
bw=Array.prototype.slice.call(bw);
bw[0].style.backgroundPosition="center 0px, " + pos + "px 0px";
};
并且它有效。但是如果我命名相同的函数并运行它:
function position() {
bw = document.getElementsByClassName("BottomWrapper");
if (bw.length===0){
bw = document.getElementsByClassName("BottomWrapper2");
}
pos = window.innerWidth/2 - 490.5;
bw=Array.prototype.slice.call(bw);
bw[0].style.backgroundPosition="center 0px, " + pos + "px 0px";
};
position();
我收到错误:
TypeError: Cannot read property 'style' of undefined
我很困惑。为什么第一个功能有效,而第二个功能无效?
最佳答案
如果 bw[0] 未定义,则意味着 document.getElementsByClassName("BottomWrapper2") 返回未定义,这很可能意味着运行脚本时 div 不在页面上。如果您在标记之后加载代码,则不会发生这种情况。
第一个可以工作的原因是它正在等待 onload 事件触发。
关于javascript - 只有 "onload"形式的 JavaScript 函数有效吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13793506/