我有一个动态定位背景图像的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
我很迷惑。为什么第一个功能起作用而不是第二个?