1
|
1 <!doctype html>
|
|
2 <html>
|
|
3 <head>
|
|
4 <meta name="viewport" content="width=device-width, initial-scale=1">
|
|
5 <style>
|
|
6 @import "/site.css";
|
|
7
|
|
8 div[drag] {
|
|
9 border: 1px solid;
|
|
10 margin: 8px;
|
|
11 padding: 8px;
|
|
12 touch-action: none;
|
|
13 background-color: LightGreen;
|
|
14 }
|
|
15 </style>
|
|
16 <script src="https://cdn.jsdelivr.net/npm/interactjs/dist/interact.js"></script>
|
|
17 <script>
|
|
18 'use strict';
|
|
19
|
|
20 let dxDrag, dyDrag;
|
|
21
|
|
22 function dragStartListener(event) {
|
|
23 dxDrag = 0;
|
|
24 dyDrag = 0;
|
|
25 }
|
|
26
|
|
27 function dragMoveListener(event) {
|
|
28 dxDrag += event.dx;
|
|
29 dyDrag += event.dy;
|
|
30 event.target.style.transform = `translate(${dxDrag}px, ${dyDrag}px)`;
|
|
31 }
|
|
32
|
|
33 function dragEndListener(event) {
|
|
34 event.target.style.transform = null;
|
|
35 }
|
|
36
|
|
37 function indexOf(a,el) {
|
|
38 for( let i=0; i<a.length; i++ ) {
|
|
39 if( a[i] === el )
|
|
40 return i;
|
|
41 }
|
|
42 return -1;
|
|
43 }
|
|
44
|
|
45 function dragEnterListener(event) {
|
|
46 console.log(event);
|
|
47 let entered = event.target;
|
|
48 let dragging = event.relatedTarget;
|
|
49 if( entered === dragging )
|
|
50 return;
|
|
51 let divs = document.querySelectorAll('div[drag]');
|
|
52 let iEntered = indexOf(divs,entered);
|
|
53 let iDragging = indexOf(divs,dragging);
|
|
54 console.log(iDragging+' '+iEntered);
|
|
55 let parent = entered.parentNode;
|
|
56 if( iDragging < iEntered ) {
|
|
57 let next = divs[iEntered+1];
|
|
58 if( next ) {
|
|
59 parent.insertBefore( dragging, next );
|
|
60 } else {
|
|
61 parent.appendChild( dragging );
|
|
62 }
|
|
63 } else {
|
|
64 parent.insertBefore( dragging, entered );
|
|
65 }
|
|
66 }
|
|
67
|
|
68 function init() {
|
|
69 let dad = interact('div[drag]');
|
|
70 dad.draggable({
|
|
71 listeners: {
|
|
72 start: dragStartListener,
|
|
73 move: dragMoveListener,
|
|
74 end: dragEndListener,
|
|
75 }
|
|
76 });
|
|
77 dad.dropzone({
|
|
78 ondragenter: dragEnterListener,
|
|
79 });
|
|
80 }
|
|
81 </script>
|
|
82 </head>
|
|
83 <body>
|
|
84 <h1><a href="https://interactjs.io/">interact.js</a></h1>
|
|
85
|
|
86 <p>This has a number of problems. First, it is clearly too complicated. And this means that it isn't on just one JavaScript file. One has to use the modern horror of <b>npm</b> to get it (which I refuse to do). The suggested way of handling dragging doesn't work when the DOM changes, as the example below shows. There is probably some complicated way around this, but I can't be bothered given the other issues.</p>
|
|
87
|
|
88 <div>
|
|
89 <script>
|
|
90 for( let i=1; i<=10; i++ ) {
|
|
91 document.write(`
|
|
92 <div drag id="${i}">${i} - drag me</div>
|
|
93 ` );
|
|
94 }
|
|
95 </script>
|
|
96 </div>
|
|
97 </body>
|
|
98 <script> init(); </script>
|
|
99 </html>
|