妙网科技 妙网科技 首页 妙网科技 网站开发 妙网科技 JQ手机端手势滑动事件代码

JQ手机端手势滑动事件代码

所属栏目: 网站开发 | 更新时间:2016-8-31 | 阅读:4958 次

移动(手机+平板)开发中经常会用到手指滑动时调用某些方法,成熟的框架如jQuery mobile,zepto等都有相关的封装,但是在一些轻量级的开发中为了应用这个左右滑动,就把这整个框架引用进来,有点杀鸡用牛刀的感觉。鉴于此,我在最近的项目开发中封装了jquery.swipe.js的插件。

用法:{left:function(){},right:function(){},up:function(){},down:function(){}}

即在手指滑动时自动判断滑动方向,并且无论怎样划动,只会有一个方向,不会有左上,右下这样的方向产生,故每次只会调用一下方向对应的回调函数。在此插件中,由于采用了敏感距离的算法,只有在划动超过该距离时才会实现指定方向的确认,否则划动被视为无效(为什么会有这样的算法?因为我们在滑动时,有可能会出现有意无意的拖动,如果手指稍微触碰一下,就有相应方向的确认,有点与现实不符,故加入了敏感距离,此插件中敏感距离为120,使用者可以自行修改)。

源码:

(function($) {
	var old = $.fn.swipe;

	$.fn.swipe = function(option) {
		var opt = {
			'left': $.noop,
			'right': $.noop,
			'up': $.noop,
			'down': $.noop
		};

		if ($.type(option) == 'string') {
			switch (option.toLowerCase()) {
				case 'left':
					if (this.data('opt').left && $.isFunction(this.data('opt').left)) {
						this.data('opt').left.call(this);
					}
					break;
				case 'right':
					if (this.data('opt').right && $.isFunction(this.data('opt').right)) {
						this.data('opt').right.call(this);
					}
					break;
				case 'up':
					if (this.data('opt').up && $.isFunction(this.data('opt').up)) {
						this.data('opt').up.call(this);
					}
					break;
				case 'down':
					if (this.data('opt').down && $.isFunction(this.data('opt').down)) {
						this.data('opt').down.call(this);
					}
					break;
				default:
					break;
			}

			return this;
		} else if ($.isPlainObject(option)) {
			var clone = {};

			//大小写不敏感处理
			$.each(option, function(k, v) {
				clone[k.toLowerCase()] = v;
			});

			$.extend(opt, clone);

			return this.each(function(index, ele) {
				//敏感距离
				var dis = 120;
				//各元素赋值,备直接触发时用
				$(ele).data('opt', $.extend({}, opt)).on('touchstart mousedown',function(e){
				    var ev=e.type=='touchstart'?e.originalEvent.touches[0]:e,
				        startX = ev.pageX,
                        startY = ev.pageY,
                        startLeft = $(this).position().left,
                        startTop = $(this).position().top,
                        start = {
                            left: startLeft,
                            top: startTop
                        },
                        disX = startX - startLeft,
                        disY = startY - startTop;
                        
                    $(document).on('touchmove.swipe.founder mousemove.swipe.founder',function(e){
                        var ev=e.type=='touchmove'?e.originalEvent.touches[0]:e;
                        
                        if (opt.left != $.noop || opt.right != $.noop) {
                            $(ele).css('left', ev.pageX - disX - $(ele).offsetParent().offset().left + 'px');
                        }
    
                        if (opt.up != $.noop || opt.down != $.noop) {
                            $(ele).css('top', ev.pageY - disY - $(ele).offsetParent().offset().top + 'px');
                        }
                        
                        e.preventDefault();
                    });
                    
                    $(document).on('touchend.swipe.founder mouseup.swipe.founder',function(e){
                        var ev=e.type=='touchend'?e.originalEvent.changedTouches[0]:e,
                            endX = ev.pageX,
                            endY = ev.pageY,
                            x = Math.abs(endX - startX),
                            y = Math.abs(endY - startY),
                            direction = null;
                        
                        //必须在指定dis大小外,消除敏感距离
                        direction = x >= y ? (endX < startX ? (Math.abs(endX - startX) > dis ? 'left' : null) : (Math.abs(endX - startX) > dis ? 'right' : null)) : (endY < startY ? (Math.abs(endY - startY) > dis ? 'up' : null) : (Math.abs(endY - startY) > dis ? 'down' : null));

                        switch (direction) {
                            case 'left':
                                if (opt.left && $.isFunction(opt.left)) {
                                    opt.left.call(ele);
                                }
                                break;
                            case 'right':
                                if (opt.right && $.isFunction(opt.right)) {
                                    opt.right.call(ele);
                                }
                                break;
                            case 'up':
                                if (opt.up && $.isFunction(opt.up)) {
                                    opt.up.call(ele);
                                }
                                break;
                            case 'down':
                                if (opt.down && $.isFunction(opt.down)) {
                                    opt.down.call(ele);
                                }
                                break;
                            default:
                                //复位
                                $(ele).animate({
                                    'left': start.left + 'px',
                                    'top': start.top + 'px'
                                });
                                break;
                        }
                        
                        $(document).off('.swipe.founder');
                    });
				});
			});
		} else {
			throw new Error('%E5%8F%82%E6%95%B0%E9%94%99%E8%AF%AF!');
		}
	};

	$.fn.swipe.noConflict = function() {
		$.fn.swipe = old;
		return this;
	};
})(jQuery);
案例:




<!DOCTYPE html>
<html>

	<head>
		<meta charset="utf-8">
		<title>手势+鼠标</title>
		<style type="text/css">
			#div1 {
				text-align: center;
				width: 100px;
				height: 100px;
				line-height: 100px;
				background: yellow;
				position: absolute;
				left: 50%;
				top: 50%;
			}
		</style>
	</head>

	<body>
		<div id="div1"></div>
		<script src="../js/jquery-2.1.1.js" type="text/javascript" charset="utf-8"></script>
		<script src="jquery.swipe.js" type="text/javascript" charset="utf-8"></script>
		<script type="text/javascript">
			$('#div1').swipe({
				left: function(){
					$(this).text('向左运动');
				},
				right: function(){
					$(this).text('向右运动');
				},
				up: function(){
					$(this).text('向上运动');
				},
				down: function(){
					$(this).text('向下运动');
				}
			});
		</script>
	</body>

</html>