vue 拖拽指令问题

问题:添加在父元素和子元素上,拖拽子元素会触发父元素拖动,子元素未被单独拖动
封装指令代码如下:

Vue.directive("drag", {
  bind: function(el) {
    let odiv = el; //获取当前元素
    console.log("####1",odiv)
    odiv.onmousedown = e => {
      console.log("####2")
      //算出鼠标相对元素的位置

      let disX = e.clientX - odiv.offsetLeft;
      let disY = e.clientY - odiv.offsetTop;

      document.onmousemove = e => {
        console.log("####3")
        //用鼠标的位置减去鼠标相对元素的位置,得到元素的位置
        let left = e.clientX - disX;
        let top = e.clientY - disY;

        //绑定元素位置到positionX和positionY上面
        e.positionX = top;
        e.positionY = left;

        //移动当前元素
        odiv.style.left = left + "px";
        odiv.style.top = top + "px";
        odiv.style.right = "auto";
        odiv.style.bottom = "auto";
        e.stopPropagation();
      };
      document.onmouseup = () => {
        document.onmousemove = null;
        document.onmouseup = null;
      };
    };
    odiv.ontouchstart = e => {
      let disX = e.touches[0].clientX - odiv.offsetLeft;
      let disY = e.touches[0].clientY - odiv.offsetTop;
      document.ontouchmove = e => {
        //用鼠标的位置减去鼠标相对元素的位置,得到元素的位置
        let left = e.touches[0].clientX - disX;
        let top = e.touches[0].clientY - disY;

        //绑定元素位置到positionX和positionY上面
        e.touches[0].positionX = top;
        e.touches[0].positionY = left;

        //移动当前元素
        odiv.style.left = left + "px";
        odiv.style.top = top + "px";
        odiv.style.right = "auto";
        odiv.style.bottom = "auto";
        e.stopPropagation();
      };
      document.ontouchend = () => {
        document.ontouchend = null;
        document.ontouchmove = null;
      };
    };
  }
});

DOM结构:

  <div class="video"  v-drag>
    
      <div class="video_control" v-drag></div>

  </div>

CSS代码:

<style lang="scss" scoped>
.video {
  position: absolute;
  top: 100px;
  left: 100px;
  right: auto;
  bottom: auto;
  z-index: 1000;

  .video_control{
    width: 48%;
    height: 48%;
    position: absolute;
    top: auto;
    left: auto;
    right: 0;
    bottom: 0;
}

}
</style>
阅读 1.3k
1 个回答

event.stopPropagation(),阻止事件冒泡

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题