一个小需求: 页面滚动到底部的时候, 隐藏按钮

需求:

  在页面上有个快速滚动按钮(用来滚动到页面底部), 如果页面到了底部, 就隐藏按钮, 一旦页面离开了底部, 显示按钮.

方案:

  页面滚动到底部很容易捕捉到, 隐藏按钮即可, 对脱离底部的检测稍有些trick, 需要一个长度2的数组队列来检测.

代码:

 1         var total_height = $(document).height() - $(window).height();
 2         var queue = [1, 1];
 3         $(window).scroll(function () {
 4             var current_pos = $(document).scrollTop();
 5             var delta = current_pos - total_height
 6             queue.push(delta);
 7             queue.shift();
 8             if (current_pos >= total_height) {
 9                 console.log('touch bottom');
10             }
11             // console.log(queue)
12             if (queue[0] == 0 && queue[1] != 0) {
13                 console.log('leave bottom');
14             }   
15         });

利用队列记录新旧位置, 只有 [0, 非0] 的情况下, 说明页面离开了底部. 并且只触发一次.

原文地址:https://www.cnblogs.com/tangkikodo/p/6112359.html