query判断页面滚动条(scroll)方向
query判断页面滚动条(scroll)
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) { //滚动到底部执行事件 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滑动,上滑和下滑只执行一次! scrollDirect(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) { //滚动到底部执行事件 console.dir("我到底部了"); } if (scrollTop == 0) { //滚动到头部部执行事件 console.dir("我到头部了"); } }
调用方法:
$(window).scroll(BottomJumpPage);
上面的方法是判断滚动轴是否滚动到底部,但是有时候,我们在做滚动加载的时候,有时候也要做某个div是否滚动到底部然后加载。那么如何判断DIV的滚动轴滚动到底部呢?
这个也需要了解几个高度:
1、div的高度 $("#某div").height();
2、滚动轴的高度 $(#某div)[0].scrollHeight
3、滚动轴到div顶部的高度 $(某div)[0].scrollTop;
书写代码如下:
$(document).ready(function (){ var nScrollHight = 0; //滚动距离总长(注意不是滚动条的长度) var nScrollTop = 0; //滚动到的当前位置 var nDivHight = $("#div1").height(); $("#div1").scroll(function(){ nScrollHight = $(this)[0].scrollHeight; nScrollTop = $(this)[0].scrollTop; if(nScrollTop + nDivHight >= nScrollHight) alert("滚动条到底部了"); }); });