之前只弄过滚动条滚到底部自动加载下一页,引入了一个别人写的infinite.js
现在功能是要类似于QQ聊天那样的到达顶部触发加载之前的聊天内容,自己试着写了一下,感觉写的好复杂,求助
我写的JS
var system ={ win : false, mac : false, xll : false }; //检测平台 var p = navigator.platform; system.win = p.indexOf("Win") == 0; system.mac = p.indexOf("Mac") == 0; system.x11 = (p == "X11") || (p.indexOf("Linux") == 0); if(system.win||system.mac||system.xll){ window.onload = function () { function onMouseWheel(ev) {/*当鼠标滚轮事件发生时,执行一些操作*/ var ev = ev || window.event; var scrollTop=$(window).scrollTop(); if(scrollTop == 0){ if(chat_page < chat_totalPages){ getChatList(++chat_page); }else{ return; } } if(ev.preventDefault){/*FF 和 Chrome*/ ev.preventDefault();// 阻止默认事件 } return false; } addEvent(document.body,'mousewheel',onMouseWheel); addEvent(document.body,'DOMMouseScroll',onMouseWheel); } function addEvent(obj,xEvent,fn) { if(obj.attachEvent){ obj.attachEvent('on'+xEvent,fn); }else{ obj.addEventListener(xEvent,fn,false); } } }else{ $(document.body).infinite().on("infinite", function() { if(chat_loading) return; chat_loading = true; setTimeout(function() { if(chat_page < chat_totalPages){ getChatList(++chat_page); }else{ return; } chat_loading = false; }, 500); //模拟延迟 }); }
infinite.js
/* =============================================================================== ************ Infinite ************ =============================================================================== */ /* global $:true */ +function ($) { "use strict"; $.fn.scrollHeight = function() { return this[0].scrollHeight; }; var Infinite = function(el, distance) { this.container = $(el); this.container.data("infinite", this); this.distance = distance || 50; this.attachEvents(); } Infinite.prototype.scroll = function() { var container = this.container; var offset = container.scrollHeight() - ($(window).height() + container.scrollTop()); if(offset <= this.distance) { container.trigger("infinite"); } } Infinite.prototype.attachEvents = function(off) { var el = this.container; var scrollContainer = (el[0].tagName.toUpperCase() === "BODY" ? $(document) : el); scrollContainer[off ? "off" : "on"]("scroll", $.proxy(this.scroll, this)); }; Infinite.prototype.detachEvents = function(off) { this.attachEvents(true); } var infinite = function(el) { attachEvents(el); } $.fn.infinite = function(distance) { return this.each(function() { new Infinite(this, distance); }); } $.fn.destroyInfinite = function() { return this.each(function() { var infinite = $(this).data("infinite"); if(infinite && infinite.detachEvents) infinite.detachEvents(); }); } }($);
用了mescroll插件,实现了下拉刷新,放弃了监控鼠标滚轮事件