这两天在做关于合同盖章的需求,要求在移动端能拖动章,并获取章的坐标。在网上也看了一些相关代码,最后整理出一份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;
}