前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >封装移动端 vue 拖拽指令

封装移动端 vue 拖拽指令

作者头像
copy_left
发布2019-08-21 16:44:23
1.1K0
发布2019-08-21 16:44:23
举报
文章被收录于专栏:方球方球

封装移动端 vue 拖拽指令

  • 通过vue自定义指令,将拖拽行为封装为指令
  • 使用transform做移动效果,需要注意元素初始值的获取,初始值为原始的 translate值,而元素所在非文档位置(pageX, pageY)
  • 通过style获取的样式都为字符串,需要通过正则和parseFloat转换为所需数值.
代码语言:javascript
复制
// 绑定类
class moveBuuild {

  constructor (private ele: any) {
    console.log(ele, 'element')
    this.ele = ele;
    this.init();
  }

  domPosition = {
    x: 0,
    y: 0
  }

  startPosition = {
      x: 0,
      y: 0
  }

  openMove = false
  transitionMove = {
      transform: `translate( 0px, 0px )`,
      background: 'red'
  }

  setMove (x = 0, y = 0){
    this.ele.style.transform = `translate( ${x}px, ${y}px )`;
    this.ele.style.background = 'red';
  }

  init () {
    this.ele.addEventListener('touchstart', (e: any) => this.start(e));
    this.ele.addEventListener('touchmove', (e: any) => this.move(e));
    this.ele.addEventListener('touchend', (e: any) => this.end(e));
    this.setMove();
  }
  
  start (e: any){
      const el = e.target;
      const { pageX, pageY } = e.changedTouches[0];
      this.startPosition = {
          x: pageX,
          y: pageY
      }
      const domPosition = el.style.transform.match(/[\d]+.?[\d]*px/igm);
      this.domPosition = {
          x: parseInt(domPosition[0].replace('px', '')),
          y: parseInt(domPosition[1].replace('px', '')),
      }
      this.openMove = true;
  }

  move(e: any){

      if( !this.openMove ){ return };
      const { pageX, pageY } = e.changedTouches[0];
      const movePoisition = {
          x: pageX,
          y: pageY
      }
      const x = movePoisition.x - this.startPosition.x + this.domPosition.x;
      const y = movePoisition.y - this.startPosition.y + this.domPosition.y;
      const moveStyle = {
          transform: `translate( ${x}px, ${y}px )`,
          background: 'red'
      }

      this.setMove(x, y);
      this.transitionMove = moveStyle;
  }

  end (e: any){
      this.openMove = false;
  }
  
}

// 配置指令
Vue.directive('move', {
  inserted: el =>{
    new moveBuuild(el);
  }
})
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019.07.29 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 封装移动端 vue 拖拽指令
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档