首页 > 代码库 > 手机端触摸的方向判断

手机端触摸的方向判断

function load(){ 
    document.addEventListener(‘touchstart‘,touch, false); 
    document.addEventListener(‘touchmove‘,touch, false); 
    document.addEventListener(‘touchend‘,touch, false); 
    
    function touch (event){ 
        var event = event || window.event; 
        var oInp = document.getElementById("inp"); 
    	var distance,clientX_start,clientX_end,
    		minRange=10;
    		this.clientX_start;
    		this.direction;

    		this.callbackFun=function(){
		    if(this.direction==‘ltr‘) {
		    	console.log(‘从左往右‘);
		    	}
		    else {
		    	console.log(‘从右往左‘);
		     }
		    }
        switch(event.type){ 
            case "touchstart": 
                clientX_start=event.touches[0].clientX;
                this.clientX_start=clientX_start;
                break; 
            case "touchend": 
		this.callbackFun();
                break; 
            case "touchmove": 
                event.preventDefault(); 
              
                clientX_end = event.changedTouches[0].clientX;
                //判断移动的方向
                distance=clientX_end-this.clientX_start;
                if(this.clientX_start+minRange<clientX_end) {
					this.direction=‘ltr‘;
                }
                else if(this.clientX_start-minRange>clientX_end){
                	this.direction=‘rtl‘;
                }
                break; 
        }   
    } 
} 

window.addEventListener(‘load‘,load, false);

  

这里已经对用户的行为进行了监听,在屏幕中用手滑动就可以执行相应的程序。

 

手机端触摸的方向判断