2010-05-14 34 views
6

下面的代码用于查找可以通过javascript滚动(body或html)的元素。如何确定“html”或“body”是否滚动窗口

var scrollElement = (function (tags) { 
     var el, $el, init; 
     // iterate through the tags... 
     while (el = tags.pop()) { 
      $el = $(el); 
      // if the scrollTop value is already > 0 then this element will work 
      if ($el.scrollTop() > 0){ 
       return $el; 
      } 
      // if scrollTop is 0 try to scroll. 
      else if($el.scrollTop(1).scrollTop() > 0) { 
       // if that worked reset the scroll top and return the element 
       return $el.scrollTop(0); 
      } 
     } 
     return $(); 
    } (["html", "body"])); 

    // do stuff with scrollElement...like: 
    // scrollElement.animate({"scrollTop":target.offset().top},1000); 

此代码工作完全当document的高度比window的高度。但是,当document的高度等于或小于window时,上述方法将而不是工作,因为scrollTop()将始终等于0.如果更新了DOM并且document的高度增加超过此值,则会出现此问题代码运行后window的高度。

另外,我通常不会等到document.ready来设置我的JavaScript处理程序(通常这会起作用)。我可能临时增加一个高的div到body强制上面的方法工作,但要求文档在IE中准备就绪(在标签关闭之前,您不能将节点添加到body元素)。欲了解更多关于document.ready“反模式”主题read this

所以,我很想找到一个解决方案,即使在document短的时候也能找到可滚动的元素。有任何想法吗?

+0

为什么不使用if($埃尔.scrollTop()> = 0)?编辑:哇只是意识到这个问题是超级老 – 2015-04-25 19:23:23

回答

7

自从我问了这个问题以来,它已经有大约5年了......但是比从来没有更好的迟到!

document.scrollingElement现在成为CSSOM规范的一部分,但在此时几乎没有实际的浏览器实现(2015年4月)。但是,您仍然可以找到该元素...

通过使用this polyfillMathias BynensDiego Perini

它实现由迭戈佩里尼(以上填充工具是更好CSSOM兼容,所以你应该使用。)这个基本的解决方案:

/* 
* How to detect which element is the scrolling element in charge of scrolling the viewport: 
* 
* - in Quirks mode the scrolling element is the "body" 
* - in Standard mode the scrolling element is the "documentElement" 
* 
* webkit based browsers always use the "body" element, disrespectful of the specifications: 
* 
* http://dev.w3.org/csswg/cssom-view/#dom-element-scrolltop 
* 
* This feature detection helper allow cross-browser scroll operations on the viewport, 
* it will guess which element to use in each browser both in Quirk and Standard modes. 
* See how this can be used in a "smooth scroll to anchors references" example here: 
* 
* https://dl.dropboxusercontent.com/u/598365/scrollTo/scrollTo.html 
* 
* It is just a fix for possible differences between browsers versions (currently any Webkit). 
* In case the Webkit bug get fixed someday, it will just work if they follow the specs. Win ! 
* 
* Author: Diego Perini 
* Updated: 2014/09/18 
* License: MIT 
* 
*/ 
function getScrollingElement() { 
    var d = document; 
    return d.documentElement.scrollHeight > d.body.scrollHeight && 
      d.compatMode.indexOf('CSS1') == 0 ? 
      d.documentElement : 
      d.body; 
} 

- getScrollingElement.js