Dav*_*och 7 javascript jquery scroll cross-browser
下面的代码用于查找可以通过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);
Run Code Online (Sandbox Code Playgroud)
当高度document大于高度时,此代码可以正常工作window.但是,当高度document相同或者小于window上述方法时将无法工作,因为它scrollTop()总是等于0.如果更新DOM并且高度document超过window后面的高度,这就成了问题.代码运行.
另外,我通常不会等到document.ready设置我的javascript处理程序(这通常有效).我可以在body临时附加一个高div来强制上面的方法工作但是要求文档在IE中准备就绪(你不能在标签关闭之前向body元素添加一个节点).有关document.ready"反模式"主题的更多信息,请阅读此内容.
所以,我很乐意找到一个解决方案,即使它document很短也能找到可滚动的元素.有任何想法吗?
Dav*_*och 12
自从我问过这个问题已经有5年了......但是迟到总比没有好!
document.scrollingElement现在是CSSOM规范的一部分,但此时几乎没有实际的浏览器实现(2015年4月).但是,您仍然可以找到该元素......
通过使用该填充工具由马蒂亚斯Bynens和迭戈佩里尼.
这由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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1818 次 |
| 最近记录: |