这就是 jQuery 的做法:
var doc = document.documentElement, body = document.body;
var left = (doc && doc.scrollLeft || body && body.scrollLeft || 0);
var top = (doc && doc.scrollTop || body && body.scrollTop || 0);
一旦你知道窗口滚动到哪里,你只需要绑定到“滚动”事件(如果没有 jQuery,绑定有点棘手,只是因为旧浏览器有不同的方法来处理事件绑定)
var addEvent = (function( window, document ) {
if ( document.addEventListener ) {
return function( elem, type, cb ) {
if ( (elem && !elem.length) || elem === window ) {
elem.addEventListener(type, cb, false );
}
else if ( elem && elem.length ) {
var len = elem.length;
for ( var i = 0; i < len; i++ ) {
addEvent( elem[i], type, cb );
}
}
};
}
else if ( document.attachEvent ) {
return function ( elem, type, cb ) {
if ( (elem && !elem.length) || elem === window ) {
elem.attachEvent( 'on' + type, function() { return cb.call(elem, window.event) } );
}
else if ( elem.length ) {
var len = elem.length;
for ( var i = 0; i < len; i++ ) {
addEvent( elem[i], type, cb );
}
}
};
}
})( this, document );
// Example Usage
addEvent( window, 'scroll', function() {
//Test scroll position and set style
});
(这是从这个页面获取的)