js-scroll判斷頁面是向上滾動還是向下滾動
原理:那當前的scrollTop和之前的scrollTop對比
如果變大了,表示向下滾動(scrollTop值變大);
如果變小了,表示向上滾動(scrollTop值變小)。
方法一:js代碼:
$(document).ready(function(){ var p=0, t=0; $(window).scroll(function(){ p=$(this).scrollTop(); if(t<p){ //下滾 }else{ //上滾 } setTimeout(function(){ t = p ; },0) }) })
方法二:
1.單純判斷滾動條方向:
function scroll(fn){ var beforeScrollTop = document.body.scrollTop, fn= fn || function(){}; window.addEventListener("scroll",function(){ var afterScrollTop = document.body.scrollTop; delta = afterScrollTop - beterScrollTop; if(delta===0){ return false; } fn(delte>0?"dowm":"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 - befterScrollTop; befterScrollTop = afterScrollTop; var scrollTop = $(this).scrollTop(); var scrollHeight = $(document).height(); var windowHeight = $(this).height(); if(scrollTop + windowHeight > scrollHeight - 10){ 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); }
調用方法:
var upflag=1;
var downflag=1;
//scroll滑動,上滑和下滑只執行1次!
crollDirect(function(direction){
if(direction == "down"){
if(downflag){
$(".footer_wrap").slideUp(200);
downlag=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){ //滾動到底部執行事件 console.dir("我到底部了") } if(scrollTop == 0){ //滾動到頭部執行事件 console.dir("我到頭部了") } }
調用方法:$(window).scroll(BottomJumpPage);
地址:https://www.cnblogs.com/liuqingxia/p/7590862.html
js-scroll判斷頁面是向上滾動還是向下滾動