<!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>
.box {
width: 100px;
height: 100px;
background-color: pink;
position: absolute;
}
.box2 {
width: 100px;
height: 100px;
background-color: red;
margin: 100px auto;
}
</style>
</head>
<body>
<div class="box"></div>
<div class="box2"></div>
<script>
// mouseup 鼠标松开
// onmousemove 鼠标移动
var box = document.querySelector(".box")
box.onmousedown = function (e) {
// 盒子的偏移量
var x = e.offsetX
var y = e.offsetY
document.onmousemove = function (e) {
var left = e.clientX - x
var top = e.clientY - y
box.style.left = left + 'px'
box.style.top = top + 'px'
}
box.onmouseup = function () {
document.onmousemove = null
box.onmouseup = null
}
}
</script>
</body>
</html>
网友评论