下面的代码用于查找可以通过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
短的时候也能找到可滚动的元素。有任何想法吗?
为什么不使用if($埃尔.scrollTop()> = 0)?编辑:哇只是意识到这个问题是超级老 – 2015-04-25 19:23:23