鼠标拖拽(1)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
div {
width: 100px;
height: 100px;
background-color: pink;
position: absolute;
left: 0;
top: 0;
}
</style>
</head>
<body>
<div></div>
<script>
var ele = document.querySelector('div')
var flag = false
ele.onmousedown = function () {
console.log('按下')
flag = true
}
ele.addEventListener('mouseup', function () {
console.log('鼠标抬起')
flag = false
})
document.onmousemove = function (e) {
if (!flag) return
var x = e.clientX - ele.offsetWidth / 2
var y = e.clientY - ele.offsetHeight / 2
ele.style.left = x + 'px'
ele.style.top = y + 'px'
}
</script>
</body>
</html>