实现div的拖拽

拖拽:在div上按下鼠标,移动鼠标,移动过程中让div跟随鼠标移动
分析:

  • 给div绑定鼠标按下事件 - 在按下的事件中继续绑定移动事件
  • div移动:设置left和top - 给div设置定位
  • left 和 top 的值是多少? 获取鼠标的位置 ,就是 left 和 top
  • left 和 top =鼠标在浏览器中位置 减去 一开始鼠标是div上的位置
	<style>
    .box{
        width: 100px;
        height: 100px;
        background-color: pink;
        position: absolute;
        left: 0;
        top: 0;
    }
	</style>
	<body>
	<div class="box"></div>
	</body>
	var box = document.querySelector('.box')
	
	// 绑定鼠标按下对象
	box.onmousedown = function() {
	
    // 获取鼠标在div上按下的位置
    var e = window.event;  //接收事件对象
	// 获取鼠标在当前事件源的位置
    var x1 = e.offsetX
    var y1 = e.offsetY
    
    // 绑定移动事件
    document.onmousemove = function() {
    
        // 获取鼠标在浏览器中的位置 - 每个事件都有自己独特的事件对象
        var e = window.event;
        var x2 = e.clientX
        var y2 = e.clientY
        
        // 计算left和top
        var l = x2 - x1
        var t = y2 - y1
        
        // 设置不能超出左上角和右上角
        if(l < 0) {
            l = 0
        }
        if(t < 0) {
            t = 0
        }
          // 设置left和top的最大值 不能超过事件源本身
        if(t > document.documentElement.clientHeight - box.offsetHeight) {
            t = document.documentElement.clientHeight - box.offsetHeight
        }
        if(l > document.documentElement.clientWidth - box.offsetWidth) {
            l = document.documentElement.clientWidth - box.offsetWidth
        }

        // 设置div的left和top
        box.style.left = l + 'px'
        box.style.top = t + 'px'
    }
}
// 拖拽行为一定要记得解绑mousemove事件
window.onmouseup = function() {
    document.onmousemove = null
}
  • 3
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值