Home Web Front-end JS Tutorial List drag sorting implementation code based on JQuery_jquery

List drag sorting implementation code based on JQuery_jquery

May 16, 2016 pm 05:20 PM
jquery

Requirements

Drag sorting, as you can imagine from the name, is to press and hold a row of data and drag it to the desired sorting position, and save the new sorting queue.

Thoughts

First create an anchor point for the list row, bind the mousedown and mouseup events, when the mouse moves to the position you want to insert, move the object row to the target row, and then sort all the rows it passes.

The idea is very simple, but there are still several issues to pay attention to

1. The position to which you move can be regarded as the position to be inserted into the target row.
2. When moving out of the top and bottom, it is judged as the first and last.
3. Processing of moving up and moving down

Solution

About the event

The mouse press and release events in Javascript are onmousedown and onmouseup. In JQuery, they are mousedown and mouseup. Therefore, mousedown and mouseup are used here

First of all, you need to know how many lines there are in the interface and how high each line is, because you need to judge the movement distance of the mouse

Copy codeThe code is as follows:

var tbodyHeight=setting.frame.outerHeight(); //setting.frame, parent object
var lineNum=$("." setting.dgLine) .length; //setting.dgLine, classname of each line
var lineHeight=Math.ceil(tbodyHeight/lineNum);

All you need to do is get lineNum (the number of lines). In addition to calculating the line height, another purpose is to use index() to move the line to the target position through the sequence index value

When the mousedown event is triggered, it is necessary to start calculating the distance of the mouse movement, which is used to determine where the line should be moved

Copy code The code is as follows:

dgid=$(this).attr(setting.id ); //The ID of the mobile row, setting.id, is the name used to mark the ID in each row
thisIndex=$("#" setting.linePre dgid).index(); //The index of the row, setting .linePre, each line ID is off
thisLineTop=$("#" setting.linePre dgid).offset().top; //The top value of this line
topDistance=thisIndex*lineHeight; //This line The distance from the top of the first line
downDistance=(lineNum-thisIndex-1)*lineHeight; //The distance between this line and the bottom of the last line


dgid is mainly used to distinguish the identifier of each line. The general list is output by the program loop. Without such an ID, it is impossible to tell which line is which. Therefore, in HTML, You need to define a person to store the ID. The program uses attr to get this value, ensuring that each row has its own unique value.

thisLineTop is mainly used to calculate the height based on the mouse movement position, and then determine which line it has moved to based on the line height and index value. Another function is to determine whether the moving anchor point is pressed. If there is a value, it means yes, and the subsequent mouseup is established. If there is no value, it means the anchor point is not pressed, and mouseup does not perform any operation. Why do this? Because no matter where you click the mouse on the page, the mouseup event will be triggered. If there is no judgment, it will continue to execute, which will cause some problems.

topDistance and downDistance are used to determine whether the mouse has moved out of the list. If it has been removed, that is, the distance the mouse moves is greater than topDistance or downDistance, it can be judged that it needs to be moved to the first or last row.

The mousedown event mainly does these few things. Of course, for the sake of effect, you can also add some things

Copy code The code is as follows:

$("#" setting.linePre dgid).css ('background',setting.lineHighlight); //Highlight mobile lines
var left=e.pageX 20;
var top=e.pageY;
dg_tips(left,top); //Create A prompt layer
$('body').css('cursor','move'); //Change the mouse gestures of the page
$("body").disableSelection(); //Disable pressing Select the page element when the mouse is moved behind the mouse
setting.frame.mousemove(function(e){ //Let the prompt layer follow the mouse movement
$("#dgf").css({"left":e. pageX setting.tipsOffsetLeft 'px',"top":e.pageY 'px'});
});

The purpose of these is just to make the operation more effective. For example, highlighting a row is to let the user know which row they are operating on. The prompt layer works the same way.

Regarding disabling selection, .disableSelection(); this is a method included in jQuery_UI. If you are using jQuery_UI, you can use it directly. If not, you can do this

Copy code The code is as follows:

$('body').each(function() {                                                                               select':'none',
'-webkit-user-select':'none',
'user-select':'none'
}).each(function() {
this.onselectstart = function() { return false; };
});
});


Cancel prohibited selection

$('body').each(function() {              ',
'user-select':''
});
});



Considering versatility, .disableSelection();
will not be used in the following code.
Okay, here is the mouseup event. The mouseup event here is bound to the body, because if the mouseup is only bound to the anchor point, when the mouse moves out of the anchor point and then releases the mouse, you will find that the mouseup event will not be executed because it will think It is a mouseup of other objects. Therefore, the safest way is to use $('body').mouseup. Basically there will be no problems.
After mouseup is triggered, you must first determine whether thisLineTop has a value to prevent meaningless event execution. Then determine whether the distance moved by the mouse is positive or negative, that is, moving up or down.

var moveDistance=e.pageY-thisLineTop;

Do different processing according to different directions

Copy code

The code is as follows:if(moveDistance<0){ if( thisIndex!=0){ moveDistance=Math.abs(moveDistance); //When it is a negative number, take the absolute value
if(moveDistance>lineHeight/2){ //Judge whether the moving distance exceeds the line height 1/2
if(moveDistance>topDistance){ //If the moving distance is greater than the distance from the row to the top edge
focusIndex=0;
}else{
focusIndex=thisIndex-Math.ceil( moveDistance/lineHeight);
}
$("." setting.dgLine).eq(focusIndex).before($("#" setting.linePre dgid));//Insert the line into the target position
}
}
}else{
if(thisIndex!=lineNum-1){
if(moveDistance>lineHeight/2 lineHeight){
if(moveDistance>downDistance){
focusIndex=lineNum-1;
}else{
focusIndex=thisIndex Math.ceil(moveDistance/lineHeight)-1;
}
$("." setting.dgLine).eq( focusIndex).after($("#" setting.linePre dgid));
}
}
}



The reason why it is judged whether the movement distance exceeds 1/2 of the row height is because if it only moves a small point, it can be regarded as not moving. When calculating the target index value, Math.ceil is used, and the carry is the most. When the moving distance is greater than 0, the carry is -1, because it is downward.

Moving up and moving down use different insertion methods, before and after. You can try to think about why before and after are used.
After moving, you still need to remove the effect used when pressing the mouse

Copy code

The code is as follows:$("#dgf").remove(); //Remove the prompt layer$("#" setting.linePre dgid).css('background','');//Convert the highlighted line to normaldgid='';// Leave the ID value of the mobile line empty
thisLineTop=0;//Change the Top value of the mobile line to 0
$('body').css('cursor','default');//Change the mouse gesture is the default



Basically this is the situation, the main problem is in handling movement and determining where to insert. Everything else is very simple.

The complete package program is given below, including the update data part

Copy code

The code is as follows:

/*
*
*  DragList.js
*  @author fuweiyi

*/
(function($){
 $.fn.DragList=function(setting){
  var _setting = {
   frame : $(this),
   dgLine : 'DLL',
   dgButton : 'DLB',
   id : 'action-id',
   linePre : 'list_',
   lineHighlight : '#ffffcc',
   tipsOpacity : 80,
   tipsOffsetLeft : 20,
   tipsOffsetTop : 0,
   JSONUrl : '',
   JSONData : {},
   maskLoaddingIcon : '',
   maskBackgroundColor : '#999',
   maskOpacity : 30,
   maskColor : '#000',
   maskLoadIcon:'',
  };
  var setting = $.extend(_setting,setting);

  var dgid='',thisIndex,thisLineTop=0,topDistance,downDistance;
  var tbodyHeight=setting.frame.outerHeight();
  var lineNum=$("."+setting.dgLine).length;
  var lineHeight=Math.ceil(tbodyHeight/lineNum);

  $("."+setting.dgButton).mousedown(function(e){
   dgid=$(this).attr(setting.id);
   thisIndex=$("#"+setting.linePre+dgid).index();
   var left=e.pageX+20;
   var top=e.pageY;
   thisLineTop=$("#"+setting.linePre+dgid).offset().top;
   topDistance=thisIndex*lineHeight;
   downDistance=(lineNum-thisIndex-1)*lineHeight;
   $("#"+setting.linePre+dgid).css('background',setting.lineHighlight);

   dg_tips(left,top);
   $('body').css('cursor','move');
   unselect();
   setting.frame.mousemove(function(e){
    $("#dgf").css({"left":e.pageX+setting.tipsOffsetLeft+'px',"top":e.pageY+'px'});
   });
  });

  $('body').mouseup(function(e){
   if(thisLineTop>0){
    var moveDistance=e.pageY-thisLineTop;
    if(moveDistance<0){
if(thisIndex!=0){
moveDistance=Math.abs(moveDistance);
if(moveDistance>lineHeight/2){
       if(moveDistance>topDistance){
        focusIndex=0;
       }else{
        focusIndex=thisIndex-Math.ceil(moveDistance/lineHeight);
       }
       $("."+setting.dgLine).eq(focusIndex).before($("#"+setting.linePre+dgid));
       dg_update(thisIndex,focusIndex);
      }
     }
    }else{
     if(thisIndex!=lineNum-1){
      if(moveDistance>lineHeight/2+lineHeight){
       if(moveDistance>downDistance){
        focusIndex=lineNum-1;
       }else{
        focusIndex=thisIndex+Math.ceil(moveDistance/lineHeight)-1;
       }
       $("."+setting.dgLine).eq(focusIndex).after($("#"+setting.linePre+dgid));
       dg_update(thisIndex,focusIndex);
      }
     }
    }
    $("#dgf").remove();
    $("#"+setting.linePre+dgid).css('background','');
    dgid='';
    thisLineTop=0;
    $('body').css('cursor','default');
    onselect();
   }
  });

  function dg_update(thisIndex,focusIndex){
   dg_mask();
   var start=thisIndex var end=thisIndex var ids='',vals='';
for(var i=start;i<=end;i++){
ids+=i==start?$("."+setting.dgLine).eq(i).attr(setting.id):','+$("."+setting.dgLine).eq(i).attr(setting.id);
vals+=i==start?i:','+i;
}
$.getJSON(setting.JSONUrl,{'do':'changeorders','ids':ids,'vals':vals},function(d){
$("#dg_mask").remove();
});
}

function dg_mask(){
var W=setting.frame.outerWidth();
var H=setting.frame.outerHeight();
var top=setting.frame.offset().top;
var left=setting.frame.offset().left;
var mask="

正在使劲的保存...
";
   $('body').append(mask);
   $("#dg_mask").css({"background":"#999","position":'absolute','width':W 'px','height':H 'px','line-height':H 'px','top':top 'px','left':left 'px','filter':'alpha(opacity=' setting.maskOpacity ')','moz-opacity':setting.maskOpacity/100,'opacity':setting.maskOpacity/100,'text-align':'center','color':'#000'});
  }

  function dg_tips(left,top){
   var floatdiv="
移动一条记录
";
   $('body').append(floatdiv);
  }

  function unselect(){
   $('body').each(function() {          
    $(this).attr('unselectable', 'on').css({
     '-moz-user-select':'none',
     '-webkit-user-select':'none',
     'user-select':'none'
    }).each(function() {
     this.onselectstart = function() { return false; };
    });
   });
  }

  function onselect(){
   $('body').each(function() {          
    $(this).attr('unselectable', '').css({
     '-moz-user-select':'',
     '-webkit-user-select':'',
     'user-select':''
    });
   });
  }
 }
})(jQuery);

使用

复制代码 代码如下:


 
  
   
   
  
 
 
  
  
   
   
  
  
 
拖动名称
这里是一行


参数主要是dgLine,dgButton,id,linePre和JSONUrl,通过看HTML代码,应该不难理解。

关于拖动排序就是这么多了,当然还可以把效果做得更漂亮些,提示更清楚点,有助于用户体验

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Detailed explanation of jQuery reference methods: Quick start guide Detailed explanation of jQuery reference methods: Quick start guide Feb 27, 2024 pm 06:45 PM

Detailed explanation of jQuery reference method: Quick start guide jQuery is a popular JavaScript library that is widely used in website development. It simplifies JavaScript programming and provides developers with rich functions and features. This article will introduce jQuery's reference method in detail and provide specific code examples to help readers get started quickly. Introducing jQuery First, we need to introduce the jQuery library into the HTML file. It can be introduced through a CDN link or downloaded

How to use PUT request method in jQuery? How to use PUT request method in jQuery? Feb 28, 2024 pm 03:12 PM

How to use PUT request method in jQuery? In jQuery, the method of sending a PUT request is similar to sending other types of requests, but you need to pay attention to some details and parameter settings. PUT requests are typically used to update resources, such as updating data in a database or updating files on the server. The following is a specific code example using the PUT request method in jQuery. First, make sure you include the jQuery library file, then you can send a PUT request via: $.ajax({u

In-depth analysis: jQuery's advantages and disadvantages In-depth analysis: jQuery's advantages and disadvantages Feb 27, 2024 pm 05:18 PM

jQuery is a fast, small, feature-rich JavaScript library widely used in front-end development. Since its release in 2006, jQuery has become one of the tools of choice for many developers, but in practical applications, it also has some advantages and disadvantages. This article will deeply analyze the advantages and disadvantages of jQuery and illustrate it with specific code examples. Advantages: 1. Concise syntax jQuery's syntax design is concise and clear, which can greatly improve the readability and writing efficiency of the code. for example,

How to remove the height attribute of an element with jQuery? How to remove the height attribute of an element with jQuery? Feb 28, 2024 am 08:39 AM

How to remove the height attribute of an element with jQuery? In front-end development, we often encounter the need to manipulate the height attributes of elements. Sometimes, we may need to dynamically change the height of an element, and sometimes we need to remove the height attribute of an element. This article will introduce how to use jQuery to remove the height attribute of an element and provide specific code examples. Before using jQuery to operate the height attribute, we first need to understand the height attribute in CSS. The height attribute is used to set the height of an element

jQuery Tips: Quickly modify the text of all a tags on the page jQuery Tips: Quickly modify the text of all a tags on the page Feb 28, 2024 pm 09:06 PM

Title: jQuery Tips: Quickly modify the text of all a tags on the page In web development, we often need to modify and operate elements on the page. When using jQuery, sometimes you need to modify the text content of all a tags in the page at once, which can save time and energy. The following will introduce how to use jQuery to quickly modify the text of all a tags on the page, and give specific code examples. First, we need to introduce the jQuery library file and ensure that the following code is introduced into the page: &lt

Use jQuery to modify the text content of all a tags Use jQuery to modify the text content of all a tags Feb 28, 2024 pm 05:42 PM

Title: Use jQuery to modify the text content of all a tags. jQuery is a popular JavaScript library that is widely used to handle DOM operations. In web development, we often encounter the need to modify the text content of the link tag (a tag) on ​​the page. This article will explain how to use jQuery to achieve this goal, and provide specific code examples. First, we need to introduce the jQuery library into the page. Add the following code in the HTML file:

Understand the role and application scenarios of eq in jQuery Understand the role and application scenarios of eq in jQuery Feb 28, 2024 pm 01:15 PM

jQuery is a popular JavaScript library that is widely used to handle DOM manipulation and event handling in web pages. In jQuery, the eq() method is used to select elements at a specified index position. The specific usage and application scenarios are as follows. In jQuery, the eq() method selects the element at a specified index position. Index positions start counting from 0, i.e. the index of the first element is 0, the index of the second element is 1, and so on. The syntax of the eq() method is as follows: $("s

How to tell if a jQuery element has a specific attribute? How to tell if a jQuery element has a specific attribute? Feb 29, 2024 am 09:03 AM

How to tell if a jQuery element has a specific attribute? When using jQuery to operate DOM elements, you often encounter situations where you need to determine whether an element has a specific attribute. In this case, we can easily implement this function with the help of the methods provided by jQuery. The following will introduce two commonly used methods to determine whether a jQuery element has specific attributes, and attach specific code examples. Method 1: Use the attr() method and typeof operator // to determine whether the element has a specific attribute

See all articles