Javascript 如何确定“是否”;html";或;正文“;滚动窗口

Javascript 如何确定“是否”;html";或;正文“;滚动窗口,javascript,jquery,cross-browser,scroll,Javascript,Jquery,Cross Browser,Scroll,下面的代码用于查找可以通过javascript滚动的元素(主体或html) var scrollElement = (function (tags) { var el, $el, init; // iterate through the tags... while (el = tags.pop()) { $el = $(el); // if the scrollTop value is alr

下面的代码用于查找可以通过javascript滚动的元素(主体或html)

    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);
文档
的高度大于
窗口
的高度时,此代码工作正常。但是,当
文档
的高度等于或小于
窗口
时,上述方法将不起作用,因为
scrollTop()
始终等于0。如果在代码运行后更新DOM并且
文档
的高度超过
窗口
的高度,则会出现问题

另外,我通常不会等到document.ready设置我的javascript处理程序(这通常是有效的)。我可以在
主体中临时添加一个高div,以强制上面的方法工作,但这需要在IE中准备好文档(在关闭标记之前,不能向主体元素添加节点)。有关
文档的详细信息,请参见“反模式”主题


因此,我想找到一个解决方案,即使
文档很短,也能找到可滚动元素。有什么想法吗?

我问这个问题已经五年了……但迟做总比不做强

document.scrollingElement
现在是CSSOM规范的一部分,但目前几乎没有真正的浏览器实现(2015年4月)。但是,您仍然可以找到元素

通过使用By和

它实现了Diego Perini的基本解决方案(上面的polyfill更好,并且符合CSSOM,因此您可能应该使用它):

-

为什么不使用if($el.scrollTop()>=0)?编辑:哇,刚刚意识到这个问题太老了
/*
 * 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;
}