开发者

To drag drop table rows using Javascript?

I am using a HTML table to show data, and I want that user can drag and drop the table rows to sort the data as per their need. The HTML code for the table:

<table id='datagrid'>
   <tbody>
      <tr>
         <td>1</td>
      </tr>
      <tr>
         <td>开发者_如何学编程2</td>
      </tr>
      <tr>
         <td>3</td>
      </tr>
   </tbody>
</table>

I want that user can drag the rows and sort as per needed... in Javascript NOTE: Don't want answer using jQuery, Mootools or any other Javascript library, because I want to use classic Javascript (i.e. the core).


The reason many people will point you towards a framework is that there are lots of browser differences for drag and drop and the framework handles all of these for you.

However, these event handlers will give you a fair start.

onDragStart - this will fire on the source element when you start to drag it somewhere.

onDrop - this will fire on the target element when you "let go" of the source element while hovering over the target element.


A table row cannot be positioned. There is no way to change the top or left values.

Instead drag a "proxy" element, such as a div.

When the mousedown occurs, if the event target is or contains something you want to drag (its a TR or has a TR ancestor that you care about), show the proxy there and assign a mousemove handler that updates the proxy coordinase.

In the mouseup event, hide the proxy (as stated) and remove the mousemove callback. If the mouseup event occurred in the table, the source TR can be inserted to the new order.

To make the operation more obvious, signifying information from the source TR, such as text inside it, can be copied to the proxy. The source TR can be greyed (by setting opacity or background color).

You might also want to provide some signifier to where the insertion will occur, when the user drops the proxy element.


This website may help you on your issue. It contains a short tutorial and working js-code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜