homework06.html 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <title></title>
  6. <style>
  7. #one, #two, #three {
  8. width: 200px;
  9. height: 200px;
  10. position: fixed;
  11. }
  12. #one {
  13. left: 50px;
  14. top: 50px;
  15. background-color: lightpink;
  16. }
  17. #two {
  18. left: 200px;
  19. top: 150px;
  20. background-color: lightgreen;
  21. }
  22. #three {
  23. right: 30px;
  24. top: 100px;
  25. background-color: lightgoldenrodyellow;
  26. }
  27. </style>
  28. </head>
  29. <body>
  30. <div id="one"></div>
  31. <div id="two"></div>
  32. <div id="three"></div>
  33. <script src="js/jquery.min.js"></script>
  34. <script>
  35. $(function() {
  36. makeDraggable($('#one'));
  37. makeDraggable($('#two'));
  38. makeDraggable($('#three'));
  39. });
  40. var draggables = [];
  41. function makeDraggable(jqElem) {
  42. draggables.push(jqElem);
  43. jqElem.on('mousedown', function(evt) {
  44. this.isMouseDown = true;
  45. this.oldX = evt.clientX;
  46. this.oldY = evt.clientY;
  47. this.oldLeft = parseInt($(evt.target).css('left'));
  48. this.oldTop = parseInt($(evt.target).css('top'));
  49. $.each(draggables, function(index, elem) {
  50. elem.css('z-index', '0');
  51. });
  52. $(evt.target).css('z-index', '99');
  53. })
  54. .on('mousemove', function(evt) {
  55. if (this.isMouseDown) {
  56. var dx = evt.clientX - this.oldX;
  57. var dy = evt.clientY - this.oldY;
  58. $(evt.target).css('left', this.oldLeft + dx + 'px');
  59. $(evt.target).css('top', this.oldTop + dy + 'px');
  60. }
  61. })
  62. .on('mouseup', function(evt) {
  63. this.isMouseDown = false;
  64. })
  65. .on('mouseout', function(evt) {
  66. this.isMouseDown = false;
  67. });
  68. }
  69. </script>
  70. </body>
  71. </html>