1.需求
做一个h5正方形的拖拽框
2.分析
使用touchstart,touchmove,touchend这3个事件实现.
需要记录的数据有三组数据,分别是下图的(x0,y0),(x1,y1),(x2,y2)。A点表示最开始的点击位置
3.代码实现
下面是html和css部分,很简单的一部分
<style> #outer{ position: relative; width: 300px; height: 300px; background: green; } #inner{ position: absolute; left: 0; top:0; width: 100px; height: 100px; background: red; } </style> <div id="outer"> <div id="inner"> </div> </div>
下面是js代码实现部分
记得要引入jq库哦!~
<script src="jquery-1.7.2.min.js"></script> <script> var outer =document.getElementById('outer'); var inner =document.getElementById('inner'); var move={ sLeft:0, sTop:0, curLeft:0, curTop:0, startX:0, startY:0, makeMove:function(e){ var e= e || window.event; var touch =e.changedTouches[0]; var x=touch.clientX; var y=touch.clientY; l = x - this.sLeft; t = y - this.sTop; //边界判断最小值 l = l<0?0:l; t = t<0?0:t; //边界判断最da值 var maxLeft = 300-100; var maxTop = 300-100; l = l>maxLeft ?maxLeft:l; t = t>maxTop?maxTop:t; move.curLeft = l; move.curTop = t; $('#inner').css({ 'left':move.curLeft +'px', 'top':move.curTop+'px' }) } } inner.addEventListener('touchstart',function(e){ //获得初始坐标 var e= e || window.event; var touch =e.changedTouches[0]; var x=touch.clientX; var y=touch.clientY; //对象属性赋值 move.sLeft = x-move.curLeft; move.sTop = y-move.curTop; move.startX=x; move.startY=y; $('#inner').css({ 'left':move.curLeft+'px', 'top':move.curTop+'px' }) },false); inner.addEventListener('touchmove',function(e){ //获得坐标 var e= e || window.event; var touch =e.changedTouches[0]; var x=touch.clientX; var y=touch.clientY; //获得偏移的值 move.makeMove(e); },false); inner.addEventListener('touchend',function(e){ },false); </script>