纯js写的移动端div拖拽方法(边界问题也解决了)

306 阅读1分钟

css部分

body{margin:0;padding:0;}
.div{position:fixed;display:block;top:0;width:70px;height:70px;background:-webkit-gradient(linear,0 0,100% 100%,from(#f00), to(#0f0));border-radius:50%;}

html部分

<div class="div" id="div"></div>

js部分

window.onload = function(){
	         var cont= document.getElementById("div"); 
	         var contW=cont.offsetWidth;
	         var contH=cont.offsetHeight;         
	         var startX,startY,sX,sY,moveX,moveY,leftX,rightX,topY,bottomY;        
	         var winW=window.screen.availWidth;
	         var winH=window.screen.availHeight;
	         console.log(winW);
	         cont.addEventListener('touchstart', touchstart, false);
	         cont.addEventListener('touchmove', touchmove, false);
	     	 function touchstart(e){                
	             startX = e.touches[0].pageX;    //获取点击点的X坐标    
	             startY = e.touches[0].pageY;    //获取点击点的Y坐标
	             sX=cont.offsetLeft;//相对于当前窗口X轴的偏移量
	             sY=cont.offsetTop;//相对于当前窗口Y轴的偏移量
	             leftX=startX-sX;//鼠标所能移动的最左端是当前鼠标距div左边距的位置
	             rightX=winW-contW+leftX;//鼠标所能移动的最右端是当前窗口距离减去鼠标距div最右端位置
	             topY=startY-sY;//鼠标所能移动最上端是当前鼠标距div上边距的位置
	             bottomY=winH-contH+topY;//鼠标所能移动最下端是当前窗口距离减去鼠标距div最下端位置                
	         };
	         function touchmove(e){                
	             e.preventDefault();
	             moveX=e.touches[0].pageX;//移动过程中X轴的坐标
	             moveY=e.touches[0].pageY;//移动过程中Y轴的坐标
	             if(moveX<leftX){moveX=leftX;}                                
	             if(moveX>rightX){moveX=rightX;}
	             if(moveY<topY){moveY=topY;}
	             if(moveY>bottomY){moveY=bottomY;}
	             cont.style.left = moveX+sX-startX + "px";
	             cont.style.top = moveY+sY-startY + "px";
	
	         };
	     };