1,思路:先写出固定的html以及css样式,再写出js操作,直接上代码内容;
2,html:
<div class="panel">
<div class="panel-title">11</div>
<div class="panel-body">22</div>
</div>
3,css样式:
* {
margin: 0;
padding: 0;
}
.panel {
width: 100px;
height: 100px;
background-color: pink;
padding: 10px;
margin: 10px;
position: absolute;
left: 50px;
top: 50px;
cursor: pointer;
}
4,js操作
// 获取当前可视窗口的宽度和高度
const _winWidth = window.innerWidth
const _winHeight = window.innerHeight
// 获取拖拽div自身的宽度和高度
const _boxWidth = document.querySelector(".panel").offsetWidth
const _boxHeight = document.querySelector(".panel").offsetHeight
// 鼠标按下事件
document.querySelector(".panel").onmousedown = function (event) {
// 获去光标在div元素坐标系中的位置(点击坐标)
const _offsetX = event.offsetX
const _offsetY = event.offsetY
// 鼠标移动时,计算拖拽元素的定位位置
document.onmousemove = function (event) {
// 当前光标在可视窗口的定位
const _clientX = event.clientX
const _clientY = event.clientY
// 计算拖拽元素的定位
let _top = _clientY - _offsetY
let _left = _clientX - _offsetX
// 判断是否超过范围,如果超过就等于临界值
if (_top < 0) {
_top = 0
} else if (_top > _winHeight - _boxHeight) {
_top = _winHeight - _boxHeight
}
if (_left < 0) {
_left = 0
} else if (_left > _winWidth - _boxWidth) {
_left = _winWidth - _boxWidth
}
// 设置元素的CSS定位
document.querySelector(".panel").style.top = _top + "px"
document.querySelector(".panel").style.left = _left + "px"
}
// 鼠标弹起,取消鼠标移动事件
document.onmouseup = function () {
document.onmousemove = null
}
}