在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
本文给大家分享一个拖拽元素时添加预览的小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> 以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持极客世界。 |
请发表评论