【问题标题】:Cross-browser method for detecting the scrollTop of the browser window检测浏览器窗口scrollTop的跨浏览器方法
【发布时间】:2009-05-16 01:01:08
【问题描述】:

检测浏览器窗口的滚动顶部的最佳跨浏览器方法是什么?我不喜欢使用任何预先构建的代码库,因为这是一个非常简单的脚本,而且我不需要所有这些无谓的东西。

【问题讨论】:

    标签: javascript cross-browser


    【解决方案1】:
    function getScrollTop(){
        if(typeof pageYOffset!= 'undefined'){
            //most browsers except IE before #9
            return pageYOffset;
        }
        else{
            var B= document.body; //IE 'quirks'
            var D= document.documentElement; //IE with doctype
            D= (D.clientHeight)? D: B;
            return D.scrollTop;
        }
    }
    
    alert(getScrollTop())
    

    【讨论】:

    • 此方法似乎不适用于 Mac 或 Linux 上的 Firefox 浏览器。
    • 丑陋的警报!改用控制台和console.log! ,无论如何都很好的答案,但是“//大多数浏览器”的浏览器支持是什么 - 或者更好的 IEwhatnumber+ 支持它?
    • 这个简短的版本是否足够正确? var scrollTop = pageYOffset || (document.documentElement.clientHeight ? document.documentElement.scrollTop : document.body.scrollTop);
    • @Roman 我认为它只会在 pageYOffset 为 0 时失败,这可能意味着根据此页面上的其他 cmets 判断,另一部分将是未定义的,所以如果你只是在末尾添加一个或 0所以它应该工作。像这样,var scrollTop = pageYOffset || (document.documentElement.clientHeight ? document.documentElement.scrollTop : document.body.scrollTop) || 0;
    • 对 Brave Browser 使用 window.pageYOffset 而不是 pageYOffset 以避免在窗口可用之前调用时出现间歇性未定义错误。
    【解决方案2】:

    或者只是简单的:

    var scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
    

    【讨论】:

    • 无法在 iPad 和可能的其他设备/浏览器(Chrome?)上运行,您需要window.pageYOffset
    • 这不是跨浏览器。
    • 适用于 mobile Safari 5 和 7、FireFox 31、Chrome 37、Opera 24、IE 5-11。根据quirksmode.org/dom/w3c_cssom.html#t35,这是so 跨浏览器。所以谢谢!简简单单。
    • 这是这里最有用的答案,甚至不需要函数(就样式而言)。
    【解决方案3】:

    如果您不想包含整个 JavaScript 库,通常可以从其中提取所需的部分。

    例如,这实际上是jQuery implements 跨浏览器滚动(上|左)的方式:

    function getScroll(method, element) {
      // The passed in `method` value should be 'Top' or 'Left'
      method = 'scroll' + method;
      return (element == window || element == document) ? (
        self[(method == 'scrollTop') ? 'pageYOffset' : 'pageXOffset'] ||
        (browserSupportsBoxModel && document.documentElement[method]) ||
        document.body[method]
      ) : element[method];
    }
    getScroll('Top', element);
    getScroll('Left', element);
    

    注意:您会注意到上面的代码包含一个未定义的browserSupportsBoxModel 变量。 jQuery defines this通过在页面中临时添加一个div,然后测量一些属性来判断浏览器是否正确实现了盒子模型。你可以想象这个标志检查 IE。具体来说,它检查IE 6 or 7 in quirks mode。由于检测相当复杂,我把它作为练习留给你;-),假设你已经在代码的其他地方使用了browserfeaturedetection

    编辑:如果您还没有猜到,我强烈建议您使用库来处理这类事情。开销是为健壮且面向未来的代码付出的很小的代价,任何人都可以通过构建跨浏览器框架来提高工作效率。 (而不是花费无数个小时来敲击 IE)。

    【讨论】:

      【解决方案4】:

      我一直在使用window.scrollY || document.documentElement.scrollTop

      window.scrollY 涵盖除 IE 之外的所有浏览器。
      document.documentElement.scrollTop 涵盖 IE。

      【讨论】:

      • 第一个表达式也可以是window.pageYOffset。我提到这一点是因为pageYOffset 似乎更具历史意义,而且我不经常看到scrollY。根据 MDN,它们是相同的。无论如何,这是迄今为止最干净和最直接的解决方案,并且应该首选,因为它首先针对现代浏览器,因此不会因为它们是最新的而受到惩罚。
      • @Jason:我的意思是补充一点,我说的是你对这个问题的回答是最干净、最直接的,而不是我自己上面的评论。
      【解决方案5】:
      function getSize(method) {
        return document.documentElement[method] || document.body[method];
      }
      getSize("scrollTop");
      

      【讨论】:

        【解决方案6】:

        YUI 2.8.1 代码这样做:

        function getDocumentScrollTop(doc) 
        {
           doc = doc || document;
        
           //doc.body.scrollTop is IE quirkmode only
           return Math.max(doc.documentElement.scrollTop, doc.body.scrollTop);
        }
        

        我认为 jQuery 1.4.2 代码(有点为人类翻译)并且假设我理解正确的话:

        function getDocumentScrollTop(doc) 
        {
           doc = doc || document;
           win = doc.defaultView || doc.parentWindow; //parentWindow is for IE < 9
        
           result = 0;
           if("pageYOffset" in win) //I'don't know why they use this, probably they tested it to be faster than doing: if(typeof win.pageYOffset !== 'undefined')
              result = win.pageYOffset;
           else
              result = (jQuery.support.boxModel && document.documentElement.scrollTop) || 
                       document.body.scrollTop;
        
           return result;
        }
        

        不幸的是,提取jQuery.support.boxModel 的值几乎是不可能的,因为您必须在文档中添加一个临时子元素并执行与 jQuery 相同的测试。

        【讨论】:

          【解决方案7】:

          我知道这个线程更新已经有一段时间了,但这是我创建的一个函数,它允许开发人员找到实际托管的根元素,它具有一个有效的“scrollTop”属性。在 Mac OS X (10.9.5) 的 Chrome 42 和 Firefox 37 上测试:

          function getScrollRoot(){
              var html = document.documentElement, body = document.body,
                  cacheTop = ((typeof window.pageYOffset !== "undefined") ? window.pageYOffset : null) || body.scrollTop || html.scrollTop, // cache the window's current scroll position
                  root;
          
              html.scrollTop = body.scrollTop = cacheTop + (cacheTop > 0) ? -1 : 1;
              // find root by checking which scrollTop has a value larger than the cache.
              root = (html.scrollTop !== cacheTop) ? html : body;
          
              root.scrollTop = cacheTop; // restore the window's scroll position to cached value
          
              return root; // return the scrolling root element
          }
          
          // USAGE: when page is ready: create a global variable that calls this function.
          
          var scrollRoot = getScrollRoot();
          
          scrollRoot.scrollTop = 10; // set the scroll position to 10 pixels from the top
          scrollRoot.scrollTop = 0; // set the scroll position to the top of the window
          

          我希望你觉得这很有用!干杯。

          【讨论】:

            【解决方案8】:

            这适用于 IE5 到 IE11。它还支持所有主要的新浏览器。

            var scrollTop = (document.documentElement && document.documentElement.scrollTop) ||
                            (document.body.scrollTop) || (document.scrollingElement);
            

            【讨论】:

            • 当滚动位置为 0 时,将其记录到控制台时将返回 &lt;body&gt;&lt;/body&gt;。最有可能发生这种情况是因为这是一个单行文件,并且 document.body.scrollTop 为 0 等于 false,因此返回了 scrollingElement。
            • 最后一项应该是document.scrollingElement.scrollTop 而不是document.scrollingElement
            【解决方案9】:

            不需要额外的库,使用这个sn-p:

            const scrollTop = 
                (window.pageYOffset !== undefined) ? 
                 window.pageYOffset :
                (document.documentElement || document.body.parentNode || document.body).scrollTop;
            

            【讨论】:

              【解决方案10】:

              我相信在现代浏览器中获取 scrollTop 的最佳方法是使用

              const scrollTop = document.scrollingElement.scrollTop
              

              如果这不起作用,您也可以尝试

              const scrollTop = Math.max(document.documentElement.scrollTop, document.body.scrollTop, document.scrollingElement.scrollTop)
              

              【讨论】:

                【解决方案11】:

                使用 jquery 或 mootools 等框架为您省去所有麻烦 在一行中计算所有这些值(跨浏览器) 在 mootools 它的 $('element').getTop(); 如果我没记错的话,在 jquery 中你需要一个名为 dimensions 的插件 尽管大多数时候即使没有框架,您实际上也可以使用 element.getScrollTop();得到你需要的东西 唯一的问题是在 IE7 下,这个计算有点错误,因为它没有考虑元素的位置值 例如,如果您有一个位置:该元素的绝对 css 属性 计算是在该元素的父元素上执行的

                【讨论】:

                • 仅供参考 - 问题指出“我不喜欢使用任何预构建的代码库”。你被标记为 mooTools 仍然是一个预构建的代码库。感谢您抽出宝贵时间做出贡献,请更彻底地阅读问题,否则您的代表会受到打击
                • 此外,这种方法的另一个问题是,如果您尝试为主窗口滚动条检测它,非 IE 浏览器将滚动 元素,而 IE 将滚动 。所以,你必须首先弄清楚“元素”是什么。
                猜你喜欢
                • 2011-06-13
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2011-11-19
                • 1970-01-01
                • 2012-01-01
                • 2015-05-16
                相关资源
                最近更新 更多