3

I just want to get the scrollTop of document and use the code from this answer. But what I get is a 'Window' object. I have tested with IE 10, Chrome and Firefox. Here is my code:

    var doc = document.documentElement, body = document.body;
    var left = (doc && doc.scrollLeft || body && body.scrollLeft || 0);
    var top = (doc && doc.scrollTop  || body && body.scrollTop  || 0);

    scroll = {
        top: (doc && doc.scrollTop  || body && body.scrollTop  || 0),
        left: (doc && doc.scrollLeft || body && body.scrollLeft || 0)
    };


    console.log(scroll.top); // return 0
    console.log(top); // return object 'Window'

I think it's a simple question but I can't figure out why it will return an object.

4

2 回答 2

3

您的变量top在窗口范围内。我可以用window.topor来引用它window.left。问题window.top已经定义。window.top指层次结构中最顶层的窗口。浏览器不允许您设置该变量。

您需要将其定义为不同的变量或更改范围,使其不与全局 [window] 命名空间冲突。

于 2013-08-28T16:48:51.357 回答
1

可能是您console.log不在声明的内部范围内var top

当您引用时,top您不会引用您声明的变量,而是引用window.top

console.log(top); // global variable `window.top`: window object

;(function(){
  var top = 0;

  console.log(top); // local variable `top`: 0

})();

console.log(top); // global variable `window.top`: window object
于 2013-08-28T16:49:48.977 回答