0
点赞
收藏
分享

微信扫一扫

自定义拖拽指令(移动端)

成义随笔 2022-03-18 阅读 90

前言

大家好,我是尤雨海。。。。。。

每次写自定义拖拽指令觉得从头写太麻烦,我自己的上传了一个简单的npm包,大家可以用一下。这是网址:

npm包地址

一、完整代码

Vue.directive("drag", {
  inserted: function (el) {
    let flags = false;
    el.ontouchstart = function (e) {
      e.preventDefault();
      flags = true;
      el.style.position = "fixed";
      let touch = e.touches[0];
      let x = touch.clientX - el.offsetLeft;
      let y = touch.clientY - el.offsetTop;
      let screenWidth = window.screen.width;
      let screenHeight = window.screen.height;
      let maxX = screenWidth - el.offsetWidth;
      let maxY = screenHeight - el.offsetHeight;
      document.ontouchmove = function (e) {
        e.preventDefault();
        if (flags) {
          let touch = e.touches[0];
          let left = touch.clientX - x;
          let top = touch.clientY - y;
          // console.log(top.left)
          if (left <= 0) {
            left = 0;
          } else if (left >= maxX) {
            left = maxX;
          }
          if (top <= 0) {
            top = 0;
          } else if (top >= maxY) {
            top = maxY;
          }
          el.style.left = left + "px";
          el.style.top = top + "px";
        }
      };
      document.ontouchend = function () {
        flags = false;
      };
    };
  },
});
举报

相关推荐

0 条评论