使用Javascript / Jquery移动节点Div Up和Down

我想知道Javascript中是否有一种方法可以在没有id的情况下上下移动节点div元素。 当选择该项目并右键单击时,会出现“上移”和“下移”选项,现在“上移”单击它应该在div中上移。

例如..

1
2
3
4
5

假设我右键单击div 3,然后Move Up选项将在那里点击Move Up它应该向上移动并且新序列应该是

  
1
3
2
4
5

感谢帮助。

这是一些例子。 试试吧。

单击项目以选择它。

 
1
2
3
4
5
Up Down

Jquery库

将此库添加到您的页面

  

jQuery的

 $(document).ready(function(){ var selected=0; var itemlist = $('#items'); var len=$(itemlist).children().length; $("#items div").click(function(){ selected= $(this).index(); alert("Selected item is " + $(this).text()); }); $("#up").click(function(e){ e.preventDefault(); if(selected>0) { jQuery($(itemlist).children().eq(selected-1)).before(jQuery($(itemlist).children().eq(selected))); selected=selected-1; } }); $("#down").click(function(e){ e.preventDefault(); if(selected < len) { jQuery($(itemlist).children().eq(selected+1)).after(jQuery($(itemlist).children().eq(selected))); selected=selected+1; } }); }); 

这是代码。 右键单击列表项并向上或向下移动。 HTML

 
  • Up
  • Down
1
  • Up
  • Down
2
  • Up
  • Down
3
  • Up
  • Down
4
  • Up
  • Down
5

CSS

 .block {width:300px;} .block > div { border:1px solid #e5e5e5; position:relative;} .contextMenu{ position:absolute; font-size:11px; width:50px; background:#e5e5e5; z-index:999; display:none;} .contextMenu ul{margin:0; padding:0; list-style:none;} .contextMenu li{border:1px solid #666; padding:5px;} 

脚本

 $('.block > div').mousedown(function(e){ if( e.button == 2 ){ $(this).find('.contextMenu').show().end().siblings('div').find('.contextMenu').hide(); }; }) $('.contextMenu li').on('click', function(){ var parentDiv = $(this).closest('div.contextMenu').parent(), dir = $(this).data('sort'); if(dir === 'up'){ parentDiv.insertBefore( parentDiv.prev() ) } else if(dir === 'down'){ parentDiv.insertAfter( parentDiv.next() ) } $('.contextMenu').hide() }); 

小提琴演示

这可能不是您想要的答案,但是看看您想要实现的目标,您可以使用jQuery UI Sortable

example here : 小提琴

 $("#downButton").click(function() { var selectedRows = $('#tblValues tr').find("td:first").find("input:checked").parents('tr'); $(selectedRows).each(function(index, item) { $(item).insertAfter($(item).next()); }); });