拖拽:在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
}