解析vue界面中可拖动<div>、<img>

在界面中拖拽某个元素,用户经历的过程是:点击,拖动,松开,即onmousedown、onmousemove、onmouseup。

div的拖动

若要拖动div,首先应在div上添加绑定事件@mousedown=“mousedown”,这样当点击div时可触发相应函数。

 <div
   width="150px" height="150px"
     @mousedown="mousedown" 
     :style="'position:fixed;left:'+left+'px;top:'+top+'px;'"/>
 </div>

在mousedown函数中首先要继续监听当前标签的onmousemove事件,当用户点击并移动时触发。此时去监控鼠标的点击位置,获取鼠标点击的窗口坐标clientX,clientY与鼠标在标签内的坐标offsetX,offsetY,通过相减即可得到标签在浏览器中的坐标(clientX-offsetX,clientY-offsetY)。并把这个坐标动态赋值给div,即实现了拖动div。最后当鼠标抬起时onmouseup销毁onmousemove事件。

public left:number=0;
public top:number=0;
 public  mousedown(e:any){
      document.onmousemove = (e2) => {
        this.left=e2.clientX-e.offsetX;
        this.top=e2.clientY-e.offsetY;
      };
      document.onmouseup = ()=> {
          document.onmousemove=null;
          document.onmousedown=null;
      };
  }

img的拖动

img标签的拖动与div的拖动思路是一样的,只是作为img标签在拖动时需要禁用浏览器默认事件。在onmousedown中引用下方函数即可

 public pauseEvent(e:any){
    if(e.stopPropagation) e.stopPropagation();//阻止把事件分派到其他节点。
    if(e.preventDefault) e.preventDefault();//阻止默认事件
    e.cancelBubble=true;//阻止冒泡
	e.returnValue=false;//阻止IE的默认事件
	return false;
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值