vue移动端拖拽浮动的icon图标

 

在右下角或者左下角的图标,有时候会遮挡住 数据,体验不是特别好。需要可拖拽、挪动。

 

结构

<div id="item_box" 
      @click="$router.push('/newAddPersonal')"
      @touchstart="getDown" 
      @touchmove="getMove"         
      @touchend="getEnd"
 >
      <img src="@/assets/common/personalVisit/icon_add.png" alt="">
</div>

  

css

#item_box{
    width:90px;
    height:90px;
    position:fixed;
    right:4%;
    bottom:10%;
}
#item_box img{
      width:100%;
      height:100%;
}

  

 

拖拽方法

data() {
    return {
      flags: false,
      position: { x: 0, y: 0 },
      nx: "",
      ny: "",
      dx: "",
      dy: "",
      xPum: "",
      yPum: "",
    };
  },
methods: {
     getDown() {
        let item_box = document.querySelector("#item_box");
        this.flags = true;
        var touch;
        if (event.touches) {
            touch = event.touches[0];
        } else {
            touch = event;
        }
        this.maxW = document.body.clientWidth - item_box.offsetWidth;
        this.maxH = document.body.clientHeight - item_box.offsetHeight;
    
        this.position.x = touch.clientX - item_box.offsetLeft;
        this.position.y = touch.clientY - item_box.offsetTop;
        this.dx = touch.clientX;
        this.dy = touch.clientY;
    },
    getMove(event) {
        event.preventDefault();
        let item_box = document.querySelector("#item_box");
        if (this.flags) {
            var touch;
            if (event.touches) {
                touch = event.touches[0];
            } else {
                touch = event;
            }
            this.nx = touch.clientX - this.position.x;
            this.ny = touch.clientY - this.position.y;
    
            if (this.nx < 0) {
                this.nx = 0;
            } else if (this.nx > this.maxW) {
                this.nx = this.maxW;
            }
    
            if (this.ny < 0) {
                this.ny = 0;
            } else if (this.ny >= this.maxH) {
                this.ny = this.maxH;
            }
    
            item_box.style.left = this.nx + "px";
            item_box.style.top = this.ny + "px";
            document.addEventListener(
                "touchmove",
                function() {
                    // event.preventDefault()
                },
                false
            );
        }
    },
    getEnd() {  this.flags = false;}
}

  

posted @ 2023-02-06 16:16  紫诺花开  阅读(408)  评论(0编辑  收藏  举报