單純判斷方向
function scroll( fn ) {
var beforeScrollTop = document.body.scrollTop,
fn = fn || function() {};
window.addEventListener("scroll", function() {
var afterScrollTop = document.body.scrollTop,
delta = afterScrollTop - beforeScrollTop;
if( delta === 0 ) return false;
fn( delta > 0 ? "down" : "up" );
beforeScrollTop = afterScrollTop;
}, false);
}
scroll(function(direction) { console.log(direction) });
以上方法手機蘋果瀏覽器事件會跳動,解決方法及代碼改進
scrollDirect: function (fn) {
var beforeScrollTop = document.body.scrollTop;
fn = fn || function () {
};
window.addEventListener("scroll", function (event) {
event = event || window.event;
var afterScrollTop = document.body.scrollTop;
delta = afterScrollTop - beforeScrollTop;
beforeScrollTop = afterScrollTop;
var scrollTop = $(this).scrollTop();
var scrollHeight = $(document).height();
var windowHeight = $(this).height();
if (scrollTop + windowHeight > scrollHeight - 10) { //滾動到底部執(zhí)行事件
fn('up');
return;
}
if (afterScrollTop < 10 || afterScrollTop > $(document.body).height - 10) {
fn('up');
} else {
if (Math.abs(delta) < 10) {
return false;
}
fn(delta > 0 ? "down" : "up");
}
}, false);
}
//調(diào)用方法
var upflag=1;
var downflag= 1;
//scroll滑動,上滑和下滑只執(zhí)行一次!
crollDirect(function (direction) {
if (direction == "down") {
if (downflag) {
$(".footer_wrap").slideUp(200);
downflag = 0;
upflag = 1;
}
}
if (direction == "up") {
if (upflag) {
$(".footer_wrap").slideDown(200);
downflag = 1;
upflag = 0;
}
}
});
滾動條滾動到底部和頭部判斷
BottomJumpPage: function () {
var scrollTop = $(this).scrollTop();
var scrollHeight = $(document).height();
var windowHeight = $(this).height();
if (scrollTop + windowHeight == scrollHeight) { //滾動到底部執(zhí)行事件
console.dir("我到底部了")梆靖;
}
if (scrollTop == 0) { //滾動到頭部部執(zhí)行事件
console.dir("我到頭部了")缸浦;
}
}
$(window).scroll(BottomJumpPage);