有个缺点;鼠标移动过快,会导致拖动失灵
var callCenterDiv = document.querySelector('#callCenterDiv')
callCenterDiv.onmousedown = function (e) {
// 记录鼠标到盒子边缘的距离,这个距离在整个拖拽过程中是固定不变的
var disX = e.offsetX, disY = e.offsetY
// 只要鼠标在box上按下了,在整个文档里移动都会触发拖拽
document.onmousemove = function (e) {
// console.log(456,e)
// 鼠标坐标减去鼠标到盒子边缘的距离
var left = e.clientX - disX
var top = e.clientY - disY
// 判断边界
if (left < 0) left = 0
if (top < 0) top = 0
if (left > window.innerWidth - callCenterDiv.offsetWidth) {
left = window.innerWidth - callCenterDiv.offsetWidth
}
if (top > window.innerHeight - callCenterDiv.offsetHeight) {
top = window.innerHeight - callCenterDiv.offsetHeight
}
callCenterDiv.style.left = left + 'px'
callCenterDiv.style.top = top + 'px'
}
// 鼠标离开box,但是仍然会触发document的up事件
document.onmouseup = function () {
// 移除move事件
document.onmousemove = null
}
// 阻止默认拖拽文字
return false
}