zoukankan      html  css  js  c++  java
  • vue中解决拖动和点击事件的冲突

    BUG说明:

    鼠标上下方向拖拽,如果松开时鼠标位于悬浮按钮上会默认执行click事件,经验证,click事件与mouse事件的执行顺序为onmousedown =》onmouseup =》onclick,意味着在click事件执行时会与与其相关的mouse事件冲突。

    解决方案:
    因为click事件执行时间短,所以利用鼠标拖动的时间差作为标志,在拖拽事件中计算鼠标从onmousedown 到onmouseup 所用的时间差,与200ms作比较,作为全局变量。由于vue的directives自定义指令中无法使用this,所以个人采用给元素设置属性的方式来解决全局变量的存储问题。

    1、自定义拖拽指令
    说明:指令中没有this关键字,指令中通过el可以直接拿到指令绑定的元素;

    directives: {
    drag: {
    // 指令的定义
    bind: function (el) {
    let odiv = el; //获取当前元素
    let firstTime='',lastTime='';
    odiv.onmousedown = (e) => {
    document.getElementById('dragbtn').setAttribute('data-flag',false)
    firstTime = new Date().getTime();
    // 算出鼠标相对元素的位置
    let disY = e.clientY - odiv.offsetTop;
    document.onmousemove = (e) => {
    // 用鼠标的位置减去鼠标相对元素的位置,得到元素的位置
    let top = e.clientY - disY;
    // 页面范围内移动元素
    if (top > 0 && top < document.body.clientHeight - 48) {
    odiv.style.top = top + 'px';
    }
    };
    document.onmouseup = (e) => {
    document.onmousemove = null;
    document.onmouseup = null;
    // onmouseup 时的时间,并计算差值
    lastTime = new Date().getTime();
    if( (lastTime - firstTime) < 200){
    document.getElementById('dragbtn').setAttribute('data-flag',true)
    }
    };
    };
    }
    }
    },
    2、悬浮菜单点击事件中进行验证。

    click(e) {
    // 验证是否为点击事件,是则继续执行click事件,否则不执行
    let isClick = document.getElementById('dragbtn').getAttribute('data-flag');
    if(isClick !== 'true') {
    return false
    }            //之后都是被阻止的代码
    if (!localStorage.settings) {
    return this.$message.error('请选择必填项并保存');
    }
    if (this.right === -300) {
    this.right = 0;
    this.isMask = true;
    } else {
    this.right = -300;
    this.isMask = false;
    }
    }

  • 相关阅读:
    node.js+mysql接口入门
    input边写边验证?正则表达式写在属性里?小技巧
    创建vue,react项目
    jquery在网页中加载本地json文件
    OpenFeigin服务接口调用
    Ribbon负载均衡服务调用
    Consul服务注册与发现
    Eureka服务注册与发现
    springboot项目在idea实现热部署
    设计模式——单例模式
  • 原文地址:https://www.cnblogs.com/xiaoleilei123/p/10669835.html
Copyright © 2011-2022 走看看