Script div implements drag and drop function of

  • 2021-07-21 06:01:58
  • OfStack

There are many dragging operations on web pages, such as dragging tree lists, draggable pictures and so on.

1. Native drag-and-drop implementation


<!doctype html>
<html lang="en">
<head>
 <meta charset="utf-8">
 <title>jQuery UI Autocomplete - Default functionality</title>
 <link rel="stylesheet" href="http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" rel="external nofollow" >
 <script src="http://code.jquery.com/jquery-1.10.2.js"></script>
 <script src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
 <style>
 .drag{
 width: 200px;
 height: 200px;
 background-color: red;
 position: absolute;
 left:0;
 top:0;
 }
 </style>
 <script>
 $(function() {
 var _move = false;// Judging whether the target object book is in a moving state 
 var _x, _y;// Mouse relative to the upper left corner of the control x.y Coordinates 
 $('.drag').click(function(event) {
 }).mousedown(function(e) {// When the left mouse button is pressed 
 _move = true;// Tag moves to true , start moving 
 _x = e.pageX - parseInt($('.drag').css('left'));// Get the upper left corner x Location of 
 _y = e.pageY - parseInt($('.drag').css('top'));// Get the upper left corner y Location of 
 $('.drag').fadeTo('20', 0.5);// Click to start dragging 
 
 });
 
 $(document).mousemove(function(e) {// Monitor mouse movement 
 if(_move) {
 var x = e.pageX - _x;// Calculate the distance of movement 
 var y = e.pageY - _y;
 $('.drag').css({top:y, left:x});
 }
 }).mouseup(function() {
 _move = false;
 $('.drag').fadeTo('fast', 1);
 });
 });
 </script>
</head>
<body>
 <div class="drag"></div>
</body>
</html>

2 jQuery UI draggable Implementation Drag and Drop

Self-implementation of the drag method is more responsible, jQuery UI provides drag events, allowing users to add drag effects to an div very simply.

jQuery UI implements the drag function primarily through the draggable event.


 <script>
 $(document).ready(function(e) {
  $('.drag').draggable({cursor: 'move'});
  $('#enable').click(function(e) {
 $('.drag').draggable('enable');
  });
  $('#disable').click(function(event) {
 $('.drag').draggable('disable');
  });
  $('#deatroy').click(function(event) {
 $('.drag').draggable('destroy');
  });
 })
 </script>
</head>
<body>
 <button id="enable">enable</button>
 <button id="disable">disable</button>
 <button id="destroy">destroy</button>
 <div class="drag">
 <p> Please drag me! </p> 
 </div>
</body>

For API of draggable, please refer to draggalbe API

draggable instance


Related articles: