可拖拽div

移动端可拖拽div

前言
移动端@touchstart @touchmove @touchend实际上对应PC得@mousedown @mousemove @mouseup
html

    <div
      class="cart-wrapper"
      @touchstart="gotouchstart"
      @touchmove="gotouchmove"
      @touchend="gotouchend"
      id="ktz"
    >
		可拖拽div
    </div>

定义变量

    return {
      clientX: 0,
      clientY: 0,
      offsetLeft: 0,
      offsetTop: 0,
      isDown: false,
    };

js

	//点击开始触发事件 获取当前所在坐标
    gotouchstart(e) {
      console.log(e);
      this.clientX = e.changedTouches[0].clientX;
      this.clientY = e.changedTouches[0].clientY;
      this.offsetLeft = e.target.offsetLeft;
      this.offsetTop = e.target.offsetTop;
      this.isDown = true;
    },
	//开始拖动div 不断获取新坐标并赋值
    gotouchmove(e) {
      console.log(e.changedTouches[0]);
      var a = e.changedTouches[0];
      console.log("wawawa");

      if (this.isDown) {
        const x = a.clientX;
        const y = a.clientY;
        let nx = x - (this.clientX - this.offsetLeft);
        let ny = y - (this.clientY - this.offsetTop);
        // document.getElementById("ktz").style.left = nx + "px"; //只允许上下拖动 
        // var height = document.getElementById("inner").offsetHeight; //获取外层div 得高度 可做判断对移动位置加以限制
        if (ny >= 0) {
          document.getElementById("ktz").style.top = ny + "px";
        }
      } else {
        return;
      }
    },
	//结束
    gotouchend(e) {
      console.log("hahah ");
      this.$nextTick(() => {
        this.isDown = false;
      });
    },

css
样式随意

.cart-wrapper {
  position: absolute;
  left: 0;
  width: 118px;
  height: 104px;
  background: #e7ebef;
  z-index: 999;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值