1. 程式人生 > >拖拽復制案例

拖拽復制案例

app demo onmouseup function mar red round utf-8 nload

<!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>



















拖拽復制案例