本文给大家分享一个拖拽元素时添加预览的小Demo,效果如下:
以下是代码实现,欢迎大家复制粘贴及吐槽。
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>原生JS实现拖拽位置预览</title> <style> .box { position: absolute; border: 1px dashed black; } #div1 { width: 100px; height: 100px; background: yellow; position: absolute; } </style> <script> window.onload = function () { var oDiv = document.getElementById('div1'); oDiv.onmousedown = function (ev) { var oEvent = ev || event; var disX = oEvent.clientX - oDiv.offsetLeft; var disY = oEvent.clientY - oDiv.offsetTop; //创建一个虚线框的div var oNewDiv = document.createElement('div'); oNewDiv.className = 'box'; //减去边框的大小与原div大小重合 oNewDiv.style.width = oDiv.offsetWidth - 2 + 'px'; oNewDiv.style.height = oDiv.offsetHeight - 2 + 'px'; oNewDiv.style.left = oDiv.offsetLeft + 'px'; oNewDiv.style.top = oDiv.offsetTop + 'px'; document.body.appendChild(oNewDiv); document.onmousemove = function (ev) { var oEvent = ev || event; oNewDiv.style.left = oEvent.clientX - disX + 'px'; oNewDiv.style.top = oEvent.clientY - disY + 'px'; }; document.onmouseup = function () { document.onmousemove = null; document.onmouseup = null; oDiv.style.left = oNewDiv.style.left; oDiv.style.top = oNewDiv.style.top; //移除虚线框 document.body.removeChild(oNewDiv); }; }; }; </script> </head> <body> <div id="div1"></div> </body> </html>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。
长按识别二维码并关注微信
更方便到期提醒、手机管理