代码语言:javascript复制
<!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>原生JS拖拽</title>
<style>
* {
margin: 0;
padding: 0;
}
.box {
position: absolute;
width: 100px;
height: 100px;
background: red;
cursor: move;
}
</style>
</head>
<body>
<div class="box" id="drag"></div>
</body>
</html>
<script>
window.onload = function () {
// 获取拖拽的节点
let drag = document.getElementById('drag')
// console.log(drag);
// 按下别拖拽对象的时候,用drag对象,move和up是全局区域,
// 也就是整个文档通用,应该使用document对象而不是drag对象。否则,采用drag对象时物体只能往右方或下方移动
// 鼠标按下时获取到drag对象
drag.onmousedown = function (event) {
// console.log(event);
// 获取window对象
var event = event || window.event;
// 鼠标点击物体那一刻相对于物体左侧边框的距离=点击时的位置相对于浏览器最左边的距离-物体左边框相对于浏览器最左边的距离
let leftX = event.clientX - drag.offsetLeft;
let leftY = event.clientY - drag.offsetTop;
// console.log(leftX, leftY);
// console.log(drag.setCapture);
if (typeof drag.setCapture !== 'undefined') {
drag.setCapture();
}
document.onmousemove = function (event) {
var event = event || window.event;
let moveX = event.clientX - leftX;
let moveY = event.clientY - leftY;
// console.log(moveX, moveY);
if (moveX < 0) {
moveX = 0;
} else if (moveX > window.innerWidth - drag.offsetWidth) {
moveX = window.innerWidth - drag.offsetWidth;
};
if (moveY < 0) {
moveY = 0;
} else if (moveY > window.innerHeight - drag.offsetHeight) {
moveY = window.innerHeight - drag.offsetHeight;
};
drag.style.left = moveX 'px';
drag.style.top = moveY 'px';
};
document.onmouseup = function (event) {
this.onmousemove = null;
this.onmouseup = null;
if (typeof drag.releaseCapture != 'undefined') {
drag.releaseCapture();
}
}
}
}
</script>