<!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>方块拖动</title> | |
<style> | |
#test{ | |
background-color: purple; | |
width: 100px; | |
height: 100px; | |
position: absolute; | |
top: 500px; | |
left: 500px; | |
} | |
</style> | |
</head> | |
<body> | |
<div id="test" draggable="true"> | |
</div> | |
<script> | |
window.οnlοad=function(){ | |
let drag =document.getElementById('test'); | |
drag.οndragstart=function(e){ | |
e=e || window.event; | |
let x=e.offsetX; | |
let y=e.offsetY; | |
document.οndragοver=function(e){ | |
e.preventDefault(); | |
} | |
document.οndrοp=function(e){ | |
drag.style.left=e.clientX-x+"px"; | |
drag.style.top=e.clientY-y+"px"; | |
} | |
} | |
} | |
</script> | |
</body> | |
</html> |
转载于:https://www.cnblogs.com/tcq43356/p/11512728.html