鼠标按下和抬起_前端JavaScript拖拽盒子跟着鼠标动

先看效果

e32cc99ba5c4298fdcaf8876be384c24.gif

简单的布局

042718e654bd53ad74eb82f97343963c.png

下面是JS代码

c91e1ac7f728ae6b3beb29bec275b6bc.png

<script>

var box = document.getElementById("box");// 获取ID

limitDrag(box);

// 拖拽封装函数

function limitDrag(node) {

// 按下

node.onmousedown = function (e) {

var e = e || window.e;

// 鼠标离盒子边框的距离 当前鼠标离浏览器左上角的距离 - 当前盒子里浏览器左上角的距离

var offsetL = e.clientX - node.offsetLeft;

var offsetT = e.clientY - node.offsetTop;

// 点击之后获取当前窗口的宽高

var windowWidth = document.documentElement.clientWidth || document.body.clientWidth;

var windowHeight = document.documentElement.clientHeight || ocument.body.clientHeight;

// 移动

this.onmousemove = function (e) {

// 当前鼠标的距离 - 鼠标按下计算出来的距离

this.style.left = e.clientX - offsetL + "px";

this.style.top = e.clientY - offsetT + "px";

// 当鼠标移出到浏览器外面的时候停止 e.clientY+20 是可能有边框滚动条距离比window.innerHeight小触发不了if

if (e.clientY + 20 >= windowHeight || e.clientX + 20 >= windowWidth || e.clientY <= 0 || e

.clientX <= 0) {

this.onmousemove = null;

}

}

}

// 鼠标抬起时让移动等于空

node.onmouseup = function (e) {

this.onmousemove = null;

var target = e.target || window.event.srcElement;

}

}

</script>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值