从本质上讲,拉动刷新仅使用劫持的 JavaScript 滚动机制公开实现,例如iScroll http://cubiq.org/iscroll-4。 Twitter 就是这样做的——使用某种 js webkit css3 滚动库。但是,您会注意到,即使在 iPhone 4 上,Twitter 在移动网络中的滚动也很卡顿,而且不是 100% 自然。
昨天,我写了一个滚动刷新处理程序overflow: scroll
成分。现在iPhone已经支持了overflow: scroll
,我们不必再劫持滚动了。当苹果修复当前的 iOS -webkit-overflow-scrolling: 触摸错误时尤其如此。
我还无法提供我的代码开源,但这是执行此操作的界面,以及一些注释。
(function(window, $, undefined) {
var hasTouch = 'ontouchstart' in window,
startEvent = hasTouch ? 'touchstart' : 'mousedown',
endEvent = hasTouch ? 'touchend' : 'mouseup';
var STATES = {
...
};
var CLASS_NAMES = {
...
};
var PullToReload = function(callback, wrapper, instructionsContent) {
// create all the dom elements and append the right before a content wrapper, but after a primary main wrapper.
// <div class="mainWrapper" style="overflow: scroll; height: 600px;"><div class="pullToReloadWrapper"></div><div class="contentWrapper"></div></div> is the markup.
// Check if the main wrapper's height is bigger than the content wrapper's height. If so, then change the main wrapper height to be the height of the content wrapper.
// scroll main wrapper by the reload wrapper's height.
// set state to pull
// invoke initEvents()
};
PullToReload.prototype.setState = function(state) {
// set the state of either pull, update, or release. Change CSS classes and content.
}
// boiler plate event handling switch
PullToReload.prototype.handleEvent = function(e) {
switch (e.type) {
case startEvent:
this.start(e);
break;
case "scroll":
this.scroll(e);
break;
case endEvent:
this.end(e);
break;
}
};
PullToReload.prototype.initEvents = function() {
// add event listeners for startEvent and endEvent with method "this"
// calling this in an event listener automatically calls handleEvent()
};
PullToReload.prototype.start = function() {
// start listening to on scroll for the wrapper
};
PullToReload.prototype.end = function(e) {
// remove scroll event listener
// if the current state is in release, then set state to update and invoke the callback,
// else the state is in pull, then invoke reset()
};
PullToReload.prototype.scroll = function(e) {
// if current scroll position is almost to the top, change state to release.
// else put it back to pull state.
};
PullToReload.prototype.reset = function() {
// animate scroll to height of reload component.
// put css classes back to the beginning
};
})(window, jQuery, I);
该解决方案适用于 iOS5、Safari、Chrome 以及其他可能的系统。我必须在几个地方使用 jQuery,主要是滚动动画。
这个解决方案不需要 css3 滚动处理程序,但只需要overflow: scroll;