思路:
拖拽 当鼠标按下的时候,获取 元素到鼠标的距离
当鼠标移动的时候 屏幕到元素的距离 = 屏幕到鼠标的距离 - 元素到鼠标的距离
当鼠标放下的时候 清空数据
带框 在布局里放两个div1,div2 ,div1隐藏,当鼠标按下的时候显示div1,移动div1,屏幕到元素的距离= div2, 鼠标放下时div1 隐藏
回放 给一个数组 把移动的数据push到数组里,点击按钮,删除尾部最后一个
案例:
<!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>
body{
margin: 0;
padding: 0;
}
#cont{
width: 200px;
height: 200px;
background: red;
position: absolute;
top: 0;
}
button{
margin-top: 300px;
}
#cborder{
border: 1px solid black;
width: 200px;
height: 200px;
position: absolute;
top: 0;
display: none;
}
</style>
</head>
<body>
<div id="cont"></div>
<div id="cborder"></div>
<button id="hui" >回放</button>
</body>
<script>
//鼠标按下 获取 元素到鼠标的距离 / 屏幕到元素的距离 /
//元素到鼠标的距离
window.onload = function (){
var div =document.getElementById('cont')
var hui =document.getElementById('hui')
var cdiv =document.getElementById('cborder')
// console.log(div)
var arr = []
div.onmousedown = function (ev){ //鼠标按下获取元素到鼠标的距离
cdiv.style.display='block'
var create_clientx = ev.clientX-cdiv.offsetLeft
var create_clienty = ev.clientY-cdiv.offsetTop
var create_clex= '';
var create_cley= '';
document.onmousemove = function (ev){
create_clex = ev.clientX-create_clientx
create_cley = ev.clientY-create_clienty
var sum ={
'clex':create_clex,
'cley':create_cley
}
arr.push(sum)
cdiv.style.left=create_clex+'px'
cdiv.style.top=create_cley+'px'
}
document.onmouseup = function (ev){//
this.onmousemove = null;
this.onmouseup = null;
cdiv.style.display='none'
div.style.left=create_clex+'px'
div.style.top=create_cley+'px'
}
}
function replay(){ //回放 鼠标移动的
if(arr.length == 1) return
var mytime = setInterval(function(){
var opot = arr.pop()
console.log(opot)
opot? (div.style.left = opot.clex+'px' , div.style.top = opot.cley+'px') : clearInterval(mytime)
},10)
}
hui.onclick = function(){
replay()
}
}
</script>
</html>