标签:efault sed UNC 对象 div str etl htc margin
第一种方式:使用H5的API dataTransfer
实现思路:
1.为将要拖拽的元素设置允许拖拽,并赋予dragstart事件将其id转换成数据保存;
2.为容器添加dragover属性添加事件阻止浏览器默认事件,允许元素放置,并赋予drop事件进行元素的放置。
代码如下:
<html> <head> <meta charset="utf-8"> <style> .box1 { width: 100px; height: 100px; border: 1px black solid; margin-bottom: 20px; background: lightblue; } .box2 { width: 100px; height: 100px; border: 1px black solid; background: lightcoral; } </style> </head> <body> <!-- 参数要传入event对象 --> <div class="box1" ondragover="allowdrop(event)" ondrop="drop(event)"> <img src="img/2.jpg" alt="00" draggable="true" ondragstart="drag(event)" id="drag" width="50" height="50"> <span>我是盒子一</span> </div> <div class="box2" ondragover="allowdrop(event)" ondrop="drop(event)"> <span>我是盒子二</span></div> <script> function allowdrop(e) { e.preventDefault(); } function drop(e) { e.preventDefault(); var data = e.dataTransfer.getData("text"); e.target.appendChild(document.getElementById(data)); } function drag(e) { e.dataTransfer.setData("text", e.target.id); } </script> </body> </html>
第二种方式:使用原生js(通过计算元素的位置结合定位实现)
思路:
<html> <head> <meta charset="utf-8"> <style> .box1 { width: 100px; height: 100px; border: 1px black solid; margin-bottom: 20px; background: lightblue; } .box2 { width: 100px; height: 100px; border: 1px black solid; background: lightcoral; } #drag { position: relative; } </style> </head> <body> <div class="box1" id="drag"> <span>我是盒子一</span> </div> <div class="box2"> <span>我是盒子二</span></div> <script> let drag = document.querySelector("#drag");//获取操作元素 drag.onmousedown = function (e) {//鼠标按下触发 var disx = e.pageX - drag.offsetLeft;//获取鼠标相对元素距离 var disy = e.pageY - drag.offsetTop; console.log(e.pageX); console.log(drag.offsetLeft); document.onmousemove = function (e) {//鼠标移动触发事件,元素移到对应为位置 drag.style.left = e.pageX - disx + ‘px‘; drag.style.top = e.pageY - disy + ‘px‘; } document.onmouseup = function(){//鼠标抬起,清除绑定的事件,元素放置在对应的位置 document.onmousemove = null; document.onmousedown = null; }; e.preventDefault();//阻止浏览器的默认事件 }; </script> </body> </html>
标签:efault sed UNC 对象 div str etl htc margin
原文地址:https://www.cnblogs.com/angle-xiu/p/11484791.html