简体   繁体   中英

How to reorder list elements in unordered list using keyboard events?

I am trying to reorder list items using Ctrl + to change the order in list in JavaScript. Please see code below:

<ul>
<li tabindex="0">item one </li>
<li tabindex="0">item two </li>
<li tabindex="0">item three </li>
<li tabindex="0">item four </li> 
</ul>

How can I do this?

This will do it:

$('li').keydown(function(e) {
  var li= $(this);
  if(e.ctrlKey) {
    switch(e.which) {
      case 38: li.insertBefore(li.prev()); break; //up
      case 40: li.insertAfter(li.next());  break; //down
    }
    li.focus();
  }
});

Fiddle

Try;

$(li1).detach().insertAfter(li2);

or

$(li1).detach().insertBefore(li2);

Use this Code with Jquery: This example uses the up arrow (38). To use the 'down' arrow, replace the 38 with 40 (in my chrome, the down arrow opens some extension function):

$(document).ready(function(){
$('body').keydown(function(e){
    if (e.ctrlKey && e.which == 38){//check if ctrl key is pressed
        var lis = $('ul > li'); //get all li's

        //order the li's
        not_ordered = new Array();
        for(i=0; i < lis.length; i++){
            not_ordered.push(lis[i].innerText);
        }
        ordered = not_ordered.sort();
        //rebuild the li's with new order:
        var new_ul_content = '';
        for(i=0; i < ordered.length; i++){
            new_ul_content += '<li tabindex="0">' + ordered[i] + ' </li>';
        }
        //replace ul content with new content:
        $('ul')[0].innerHTML = new_ul_content;
    }

});

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM