美文网首页
拖拽 vue 自定义指令

拖拽 vue 自定义指令

作者: 瘾_95f1 | 来源:发表于2020-05-30 14:34 被阅读0次
    /**
     * 
     * @param {*} el
     * @example <div v-drag></div> 
     * @example <div v-drag="[1,2,3,4]"></div> 上 右 下  左 边界 
     */
    export const drag = (el, binding) => {
      el.style.position = "fixed!important";
      let startX, startY, touchX, touchY;
      const elWidth = el.offsetWidth;
      const elHeight = el.offsetHeight;
      const limit = binding.value || [0, 0, 0, 0];
      el.ontouchstart = e => {
        // e.preventDefault();
        startY = el.offsetTop;
        startX = el.offsetLeft;
        touchX = e.touches[0].clientX;
        touchY = e.touches[0].clientY;
      }
      el.ontouchmove = e => {
        const currTouchX = e.touches[0].clientX;
        const currTouchY = e.touches[0].clientY;
        e.cancelBubble = true;
        const posL = currTouchX - touchX + startX;
        const posT = currTouchY - touchY + startY;
        const posR = posL + elWidth;
        const posB = posT + elHeight;
        if (posL >= limit[3] && posR <= (document.documentElement.clientWidth - limit[1])) {
          el.style.left = (currTouchX - touchX + startX) + 'px';
        }
        if (posT >= limit[0] && posB <= (document.documentElement.clientHeight - limit[2])) {
          el.style.top = (currTouchY - touchY + startY) + 'px';
        }
        e.preventDefault();
      }
    }
    

    相关文章

      网友评论

          本文标题:拖拽 vue 自定义指令

          本文链接:https://www.haomeiwen.com/subject/jaoczhtx.html