这里拖拽分为两种,一种是拖拽元素,实现与某个区域的交互,比如拖拽某张图片到区域中,该区域添加图片元素;第二种是拖动元素到任意位置,比如验证码拖动滑块的效果。
第一个场景主要是HTML5新增的拖拽方法draggable来实现;第二个拖动元素则通过mousedown, mousemove, mouseup来实现
拖拽添加
demo:
参考文章:
https://www.zhangxinxu.com/wordpress/2011/02/html5-drag-drop-%E6%8B%96%E6%8B%BD%E4%B8%8E%E6%8B%96%E6%94%BE%E7%AE%80%E4%BB%8B/
https://www.youtube.com/watch?v=j0vd6Syc7SQ&list=PLMN9fM-0gQ90NMxWjL2xnWQoFh-28pwa_&index=26&t=326s&ab_channel=DansonLin
https://developer.mozilla.org/zh-CN/docs/Web/API/HTML_Drag_and_Drop_API
https://developer.mozilla.org/zh-CN/docs/Web/API/HTML_Drag_and_Drop_API/Drag_operations
移动元素位置
借助mousedown, mousemove, mouseup三个事件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| <style> .container { position: relative; width: 300px; height: 200px; border: 1px solid #ddd; }
.square { position: absolute; top: 0; left: 0; width: 50px; height: 50px; background: lime; } </style>
<div class="container"> <div class="square"></div> </div>
<script> const square = document.querySelector(".square"); const container = document.querySelector(".container"); const containerLeft = container.offsetLeft; const containerTop = container.offsetTop;
square.addEventListener("mousedown", (e) => { const mouseLeft = e.pageX - containerLeft - square.offsetLeft; const mouseTop = e.pageY - containerTop - square.offsetTop;
function move(e) { square.style.left = e.pageX - containerLeft - mouseLeft + "px"; square.style.top = e.pageY - containerTop - mouseTop + "px"; }
document.addEventListener("mousemove", move);
document.addEventListener("mouseup", () => { document.removeEventListener("mousemove", move); }); }); <script>
|
鼠标点击位置的计算关系如图:
