0

我有一个动态定位背景图像的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

我很迷惑。为什么第一个功能起作用而不是第二个?

4

2 回答 2

3

如果 bw[0] 未定义,则意味着 document.getElementsByClassName("BottomWrapper2") 返回未定义,这很可能意味着运行脚本时 div 不在页面上。如果您在标签之后加载代码,则不应发生这种情况。

第一个工作的原因是因为它正在等待 onload 事件触发。

于 2012-12-10T00:42:49.117 回答
0

如果您使用这样的功能,它将起作用

<html><head>
<script>

function position() {
  bw = document.getElementsByClassName("BottomWrapper");
  console.log(bw);
  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";
  console.log(bw[0]);
};
   </script>
<body onload="position()">
<div class="BottomWrapper2"></div>
</body></head></html>

前面的会导致错误,因为在加载主体之前调用了该函数

于 2012-12-10T00:52:00.300 回答