JS拖拽位置预览 原生JS实现拖拽位置预览
aiguangyuan 人气:0想了解原生JS实现拖拽位置预览的相关内容吗,aiguangyuan在本文为您仔细讲解JS拖拽位置预览的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:js拖拽位置预览,js拖拽预览,js预览,下面大家一起来学习吧。
本文给大家分享一个拖拽元素时添加预览的小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>
加载全部内容