
<!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>拖动测试</title>
</head>
<style>
body,
html {
margin: 0;
padding: 0;
}
</style>
<body>
<div style="width: 100%;height: 100px;position: relative;" id="dragId">
<div style="width: 200px;height: 200px;background: red;position: absolute;" class="drag" draggable="true">1</div>
<div style="width: 200px;height: 200px;background: orange;position: absolute;top: 200px;left: 100px;" class="drag" draggable="true">2</div>
<div style="width: 200px;height: 200px;background: aqua;position: absolute;top: 400px;left: 200px;" class="drag" draggable="true">3</div>
</div>
</body>
</html>
<script>
let dragId = document.getElementById("dragId");
let drag = document.getElementsByClassName("drag");
let my = 0, mx = 0;
let container = null;
function dragFun(params) {
for (let i = 0; i < drag.length; i++) {
drag[i].onmousedown = function (event) {
let offsetTop = this.offsetTop, offsetLeft = this.offsetLeft;
my = event.clientY - offsetTop
mx = event.clientX - offsetLeft
}
drag[i].ondragstart = function () {
container = this;
}
drag[i].ondragend = function (event) {
event.stopPropagation();
this.style.top = (event.clientY - my) + 'px'
this.style.left = (event.clientX - mx) + 'px'
if(event.clientY - my <0){
this.style.top = '0px'
}
if(event.clientX - my <0){
this.style.left = '0px'
}
let clientHeight = document.documentElement.clientHeight-this.offsetHeight
let clientWidth = document.body.offsetWidth-this.offsetHeight || document.documentElement.clientWidth-this.offsetHeight
if(event.clientY - my > clientHeight){
this.style.top = clientHeight + 'px';
}
if(event.clientX - mx > clientWidth){
this.style.left = clientWidth + 'px';
}
}
drag[i].ondrop = function () {
if (container != null && container != this) {
let temp = document.createElement("div");
dragId.replaceChild(temp, this);
dragId.replaceChild(this, container);
dragId.replaceChild(container, temp);
}
}
drag[i].ondragover = function () {
event.preventDefault();
}
}
}
dragFun()
</script>