Appearance
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#container {
position: relative;
width: 300px;
height: 200px;
border: 3px solid black;
margin: 0 auto;
}
#box1 {
width: 100px;
height: 100px;
background-color: pink;
position: absolute;
cursor: move;
}
</style>
</head>
<body>
<div id="container"></div>
<div id="box1"></div>
<script>
function move (event) {
let curX = event.pageX,
curY = event.pageY,
curL = curX - this.startX + this.startL,
curT = curY - this.startY + this.startT,
minL = 0,
minT = 0,
maxL = document.documentElement.clientWidth - this.offsetWidth,
maxT = document.documentElement.clientHeight - this.offsetHeight
// 边界判断
curT = curT < minT ? minT : (curT > maxT ? maxT : curT)
curL = curL < minL ? minL : (curL > maxL ? maxL : curL)
this.style.top = curT + 'px'
this.style.left = curL + 'px'
}
function up () {
document.removeEventListener('mousemove', this._move)
document.removeEventListener('mouseup', this._up)
// 容器的范围
let minL = container.offsetLeft,
minT = container.offsetTop,
maxL = minL + container.offsetWidth - this.offsetWidth,
maxT = minT + container.offsetHeight - this.offsetHeight
curL = this.style.left.slice(0, -2),
curT = this.style.top.slice(0, -2)
if ((curL >= minL && curL <= maxL) && (curT >= minT && curT <= maxT)) {
// 在范围内, 成为子元素
container.appendChild(this)
this.style.top = 0
this.style.left = 0
this.removeEventListener('mousedown', down)
} else {
// 不在指定范围
this.style.top = this.startT + 'px'
this.style.left = this.startL + 'px'
}
}
function down (event) {
this.startX = event.pageX,
this.startY = event.pageY,
this.startL = this.offsetLeft,
this.startT = this.offsetTop
this._move = move.bind(this)
this._up = up.bind(this)
document.addEventListener('mousemove', this._move)
this.addEventListener('mouseup', this._up)
}
box1.addEventListener('mousedown', down)
</script>
</body>
</html>