Page 49 - JavaScript修炼之道
P. 49

任务16  实现“无限翻页”             37


                   判断是否已滚动到足够低


                    ui/infinite/infinite.js

                   function lowEnough() {
                     var pageHeight = Math.max(document.body.scrollHeight,
                       document.body.offsetHeight);
                     var viewportHeight = window.innerHeight ||
                       document.documentElement.clientHeight ||
                       document.body.clientHeight || 0;
                     var scrollHeight = window.pageYOffset ||
                       document.documentElement.scrollTop ||
                       document.body.scrollTop || 0;
                     // 在离页面底端20像素时触发翻页
                     return pageHeight - viewportHeight - scrollHeight < 20;
                   }

                   监测滚动位置并载入更多内容

                    ui/infinite/infinite.js

                   function checkScroll() {
                     if (!lowEnough()) return pollScroll();
                     $('spinner').show();
                     new Ajax.Updater('posts', 'more.php', {
                       method: 'get', insertion: 'bottom',
                       onComplete: function() { $('spinner').hide(); },
                       onSuccess: pollScroll
                     });
                   }

                   function pollScroll() { setTimeout(checkScroll, 100); }

                   pollScroll();
   44   45   46   47   48   49   50   51   52   53   54