js基础之拖拽
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
* {
padding: 0;
margin: 0;
}
.container {
width: 200px;
height: 200px;
background: red;
position: absolute;
}
</style>
</head>
<body>
<div class="container"></div>
<script>
var div = document.querySelector("div")
const width = document.documentElement.clientWidth || document.body.clientWidth
const height = document.documentElement.clientHeight || document.body.clientHeight
var maxLeft = width - div.offsetWidth,
maxTop = height - div.offsetHeight
div.onmousedown = (e) => {
e = e || window.event
// 获取鼠标距离div边缘
var disX = e.offsetX,
disY = e.offsetY
document.onmousemove = (e) => {
e = e || window.event
//鼠标距离屏幕边缘-鼠标距离div边缘
var _left = e.clientX - disX,
_top = e.clientY - disY
// 判断不能超出屏幕边界
if(_left < 0) _left = 0
if(_top < 0) _top = 0
if(_left > maxLeft) _left = maxLeft
if(_top > maxTop) _top = maxTop
div.style.left = _left + "px"
div.style.top = _top + "px"
}
// 鼠标抬起,解绑move事件
document.onmouseup = () => {
document.onmousemove = null
}
return false
}
</script>
</body>
</html>
效果如下: