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>
#box1 {
width: 100px;
height: 100px;
background-color: pink;
position: absolute;
cursor: move;
}
</style>
</head>
<body>
<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)
}
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>