下面的代码用于通过 javascript 查找可以滚动的元素(body 或 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);
当 document
的高度大于 window
的高度时,此代码可以完美运行。但是,当 document
的高度等于或小于 window
时,上述方法将不起作用,因为 scrollTop()
将始终等于 0。如果 DOM 更新并且 document
的高度增长超过代码后 window
的高度,这将成为一个问题运行。
此外,我通常不会等到 document.ready 来设置我的 javascript 处理程序(这通常有效)。我可以暂时将一个高大的 div 附加到 body
以强制上面的方法工作但是这需要文档在 IE 中准备好(你不能添加节点标签关闭前的 body 元素)。有关 document.ready
“反模式”主题的更多信息 read this .
所以,我很想找到一种解决方案,即使 document
很短,也能找到可滚动元素。有什么想法吗?
最佳答案
我问这个问题已经有 5 年了......但迟做总比不做好!
document.scrollingElement
现在是 CSSOM 规范的一部分,但目前(2015 年 4 月)几乎没有实际浏览器实现。但是,您仍然可以找到该元素...
通过使用 this polyfill通过 Mathias Bynens和 Diego Perini .
它实现了 Diego Perini 的这个基本解决方案(上面的 polyfill 更好并且符合 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;
}
关于javascript - 如何判断是 "html"还是 "body"滚动窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2837178/