<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document
</title>
<style>
div {
position: relative;
left: 100px;
top: 10px;
width: 300px;
height: 300px;
background-color: green;
}
</style>
</head>
<body>
<div></div>
<script>
var div = document.querySelector('div');
div.addEventListener('mousedown', function (e) {
var borderinx = e.pageX - div.offsetLeft;
var borderiny = e.pageY - div.offsetTop;
document.addEventListener('mousemove', move);
function move(e) {
div.style.left = e.pageX - borderinx + 'px';
div.style.top = e.pageY - borderiny + 'px';
}
document.onmouseup = function () {
document.removeEventListener('mousemove', move);
}
});
</script>
</body>
</html>
遇到两个问题,都比较有意义 **
1.pagex,offsetleft等值都是数值,必须要添加px才起作用2.解绑事件的对象不要弄错了
**
转载请注明原文地址:https://tech.qufami.com/read-27896.html