1. 程式人生 > >移動端圖標拖動並獲取移動後的坐標

移動端圖標拖動並獲取移動後的坐標

nal 坐標 posit 移動端 top 一次 target eve pan

這兩天在做關於合同蓋章的需求,要求在移動端能拖動章,並獲取章的坐標。在網上也看了一些相關代碼,最後整理出一份demo。整理的匆忙,代碼仍存在bug,當第一次移動章手指擡起後,
再次點擊一下章,坐標將改變,這點後期仍待改進。

$(function(){ var cirX=0;//圓心X橫坐標 var cirY=0;//圓心Y縱坐標 var moveX=0;//移動中觸點X橫坐標 var moveY=0;//移動中觸點Y縱坐標 var boxW=$(".box").width();//章寬 var boxH=$(".box").height();//章高 // console.log(boxW+" "+boxH); //半章寬,半章高 var halfW=$(".box").width()/2; var halfH=$(".box").height()/2; // console.log(halfW+" "+halfH); var conW=$(".con").width();//con寬 var conH=$(".con").height();//con高 // console.log(conW+" "+conH); var conX=0;//距離左邊屏幕距離 var conY=0;//距離頂部距離 conX=$(".con").offset().left;//距離左邊屏幕距離 conY=$(".con").offset().top;//距離頂部距離 // console.log(conX+" "+conY); $(".con").on(‘touchstart‘,function(e){ var move_left = e.originalEvent.targetTouches[0].pageX; //獲取觸點X橫坐標 var move_top = e.originalEvent.targetTouches[0].pageY; //獲取觸點Y縱坐標 }); $(".con").on(‘touchmove‘,function(e){ // e.preventDefault(); moveX=e.originalEvent.targetTouches[0].pageX;//移動過程中X軸的坐標 moveY=e.originalEvent.targetTouches[0].pageY;//移動過程中Y軸的坐標 // console.log(moveX +‘|‘+ moveY); cirX=moveX-conX-halfW; cirY=moveY-conY-halfH; // console.log(cirX +‘|‘+ cirY); // 判斷 if(cirX
<0){ cirX = 0; } if(cirX>conW-boxW){ cirX = conW-boxW; } if(cirY<0){ cirY = 0; } if(cirY>conH-boxH){ cirY = conH-boxH; } $(".box").css({ "left":cirX, "top":cirY, }) }); $(".con").on(‘touchend‘,function(e){ cirX=cirX+halfW; cirY=conH-(cirY+halfH); console.log(cirX +‘|‘+ cirY); }); })

<div class="con">
  <div class="box"></div>
  <img src="images/eg.png" class="imgShow"/>
</div>
.con{
	width: 300px;
	height: 400px; 
	overflow: hidden;
	border: 1px solid orange;
	margin: 10px auto 0;
	position: relative;
	text-align: center;
}
.box{
	width: 60px;
	height: 60px;
	background: red;
	opacity: .6;
	position: absolute;
	left: 0;
	top: 0;
	border-radius: 50%;
	z-index: 10;
}
.imgShow{
	max-width: 100%;
	height: auto;
	position: relative;
	top: 0;
	left: 0;
	z-index: 1;
}

移動端圖標拖動並獲取移動後的坐標