<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
*{
margin:0;
padding:0;
}
#demo{
width:300px;
height:400px;
background-color: blue;
position: absolute;
margin-left:-150px;
left:50%;
top:50%;
margin-top:60px;
}
#demo1{
width:100%;
height:100px;
background-color: red;
cursor: move;
}
</style>
</head>
<body>
<div id="demo">
<div id="demo1"></div>
</div>
</body>
</html>
<script>
//1注册事件
window.onload = function () {
//1,获取操作元素
const demo = document.querySelector("#demo");
const demo1 = document.querySelector("#demo1");
//2,然后注册鼠标按下的事件---根据事件对象来处理
demo1.onmousedown = function (e) {
e = e||window.event;
//1,获取盒子里面的位置信息--当前盒子的
const boxX = getPage(e).pageX-demo.offsetLeft;
const boxY = getPage(e).pageY-demo.offsetTop;
//2然后注册一个鼠标移动的事件
document.onmousemove = function (e) {
e = e||window.event;
const x = getPage(e).pageX - boxX;
const y = getPage(e).pageY - boxY;
//然后赋值回去
// demo.style.left = (x+150)+"px";
// demo.style.top = (y-60)+"px";
//克隆一个元素
const News = demo.cloneNode(true);
//最后处理完了之后就是设置清除事件---就是设置对象的值为null
document.onmouseup = function (e) {
e = e||window.event;
//设置位置信息
News.style.left = (x+150)+"px";
News.style.top = (y-60)+"px";
//追加到页面
document.documentElement.appendChild(News);
//设置颜色变化
News.style.background = "purple";
document.onmousemove = null;
};
};
//然后封装一个page事件
function getPage(e) {
return{
pageX:e.pageX||e.clientX+document.documentElement.scrollLeft,
pageY:e.pageY||e.clientY+document.documentElement.scrollTop
}
}
};
}
</script>