jQuery实现的上拉刷新功能组件示例

2020-05-29 07:30:00易采站长站整理

本文实例讲述了jQuery实现的上拉刷新功能组件。分享给大家供大家参考,具体如下:

技术要点:

1、jQuery的插件写法

2、上拉刷新步骤分解

3、css样式

jQuery的插件写法:


$.fn.pluginName = function() {
return this.each(function () {
fn();
})
};

上拉刷新步骤分解:

上拉刷新可以分解成三个部分:一是开始(start),记录当前鼠标的位置;二是移动(move),根据下拉的位移响应不同的视图;三是结束(end),刷新页面。


;!function ($) {
"use strict";
var PTR = function (ele) {
this.container = $(ele);
this.container.addClass('pull-to-refresh');
this.distance = 60; // 设置参考的下拉位移
this.attachEvent();
};
// 判断是否有touch事件发生
var isTouch = (function () {
var isSupportTouch = !!'ontouchstart' in document || window.documentTouch;
return isSupportTouch;
})();
var touchEvents = {
start: isTouch ? 'touchstart': 'mousedown',
move: isTouch ? 'touchmove':'mousemove',
end: isTouch ? 'touchend': 'mouseup'
};
// 获取事件发生时相对于文档的距离(含滚动距离)
function getTouchPosition(e) {
var e = e.orinalEvent || e;
console.log(e)
if(e.type === 'touchstart' || e.type === 'touchmove' || e.type === 'touchend') {
return {
x: e.targetTouches[0].pageX,
y: e.targetTouches[0].pageY
}
}else {
return {
x: e.pageX,
y: e.pageY
}
}
};
PTR.prototype.touchStart = function (e) {
var p = getTouchPosition(e);
this.start = p;
this.diffX = this.diffY = 0;
};
PTR.prototype.touchMove = function (e) {
if(this.container.hasClass('refreshing')) return;
if(!this.start) return false;
var p = getTouchPosition(e);
this.diffX = p.x - this.start.x;
this.diffY = p.y - this.start.y;
if(this.diffY < 0) return;
this.container.addClass('touching');
e.preventDefault();
e.stopPropagation();
// 设置container的位移小于页面滚动的距离,给人一种用力下拉的错觉,提升用户体验
this.diffY = Math.pow(this.diffY, .8);
this.container.css('transform', 'translate3d(0,'+ this.diffY +'px, 0)');
if(this.diffY < this.distance) {
this.container.removeClass('pull-up').addClass('pull-down')
}else {
this.container.removeClass('pull-down').addClass('pull-up')
}
};
PTR.prototype.touchEnd = function (e) {
var _this = this;
this.start = false;
this.container.removeClass('pull-down');