剛好閑了一下,於是就寫了一個js拖動div的簡單例子,項目是vue搭建的大概就是以下內容
html部分
<div class="shop-cart-icon" id="shopCart" @touchstart="touchStart($event)" @touchmove="touchMove($event)" @touchend="touchEnd($event)"></div>
js部分
data(){ return{ x:0, y:0, cart:null, startX:0, startY:0, } }, mounted(){ this.cart=document.getElementById('shopCart'); }, methods:{ touchStart(e){ e.preventDefault(); this.startX=e.changedTouches[0].clientX; this.startY=e.changedTouches[0].clientY; }, touchMove(e){ this.x=e.changedTouches[0].clientX; this.y=e.changedTouches[0].clientY; let l=this.startX-this.x; let t=this.startY-this.y; this.cart.style.transform=`translate3d(${-l}px,${-t}px,0)`; }, touchEnd(e){ let x=e.changedTouches[0].clientX; let y=e.changedTouches[0].clientY; //goShopCart if(this.startX===x&&this.startY===y){ this.goShopCart(); }else{ this.startX=e.changedTouches[0].clientX; this.startY=e.changedTouches[0].clientY; this.cart.style.right=0; this.cart.style.bottom=0; this.cart.style.transform='translate3d(0,0,0)'; this.cart.style.left=this.startX-20+'px'; this.cart.style.top=this.startY-20+'px'; } }, }
因為本身元素定位時用了right和bottom,所以在手指離開的時候就直接給他歸零掉,用做left和top,這樣就不用去做其他太多計算。