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 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
| <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <style> #one, #two, #three { width: 200px; height: 200px; position: fixed; } #one { left: 50px; top: 50px; background-color: lightpink; } #two { left: 200px; top: 150px; background-color: lightgreen; } #three { right: 30px; top: 100px; background-color: lightgoldenrodyellow; } </style> </head> <body> <div id="one"></div> <div id="two"></div> <div id="three"></div> <script src="js/jquery.min.js"></script> <script> $(function() { makeDraggable($('#one')); makeDraggable($('#two')); makeDraggable($('#three')); }); var draggables = []; function makeDraggable(jqElem) { draggables.push(jqElem); jqElem.on('mousedown', function(evt) { this.isMouseDown = true; this.oldX = evt.clientX; this.oldY = evt.clientY; this.oldLeft = parseInt($(evt.target).css('left')); this.oldTop = parseInt($(evt.target).css('top')); $.each(draggables, function(index, elem) { elem.css('z-index', '0'); }); $(evt.target).css('z-index', '99'); }) .on('mousemove', function(evt) { if (this.isMouseDown) { var dx = evt.clientX - this.oldX; var dy = evt.clientY - this.oldY; $(evt.target).css('left', this.oldLeft + dx + 'px'); $(evt.target).css('top', this.oldTop + dy + 'px'); } }) .on('mouseup', function(evt) { this.isMouseDown = false; }) .on('mouseout', function(evt) { this.isMouseDown = false; }); } </script> </body> </html>
|