js实现移动端图标拖拽效果

983 阅读1分钟

最近在做vue项目中有一个图标拖拽的效果,长按拖动图标会拖拽,点击跳转到指定页面。为了项目优化的考虑,也是为了能提高自己,所以用原生写了一个,以下是我的源码。

move(e){
    let date = new Date().getTime()
    let odiv = document.querySelector('.policy')        //获取目标元素
    //算出鼠标相对元素的位置
    e.preventDefault()
    let disX = e.targetTouches[0].clientX - odiv.offsetLeft;
    let disY = e.targetTouches[0].clientY - odiv.offsetTop;
    odiv.addEventListener('touchmove',(e)=>{       //鼠标按下并移动的事件
        //用鼠标的位置减去鼠标相对元素的位置,得到元素的位置
        let left = e.targetTouches[0].clientX - disX;    
        let top = e.targetTouches[0].clientY - disY;
                
        //移动当前元素
        odiv.style.bottom = '';
        odiv.style.right = '';
        odiv.style.left = left + 'px';
        odiv.style.top = top + 'px';
    },true)
    odiv.addEventListener('touchend',(e) => {
        if(new Date().getTime()-date < 200) this.jumpPolicy()
        odiv.removeEventListener('touchmove')
        odiv.removeEventListener('touchend')
    },true)
}  

在图标上加上这个move事件就ok

<template>
  <div class="policy" @touchstart="move">
    <img src="https://gaia-vivofs.vivo.com.cn/qEiqKoT2I4DBQpyI/21e550d0-70cb-11ea-b6ad-5bc5b85f1113.png.webp" class="policy_icon"/>
  </div>
</template>