我正在嘗試使用來重新排列列表項目Ctrl + ↓要更改JavaScript中的列表順序。請參閱下面的代碼:如何使用鍵盤事件重新排列無序列表中的列表元素?
<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>
我該怎麼做?
我正在嘗試使用來重新排列列表項目Ctrl + ↓要更改JavaScript中的列表順序。請參閱下面的代碼:如何使用鍵盤事件重新排列無序列表中的列表元素?
<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>
我該怎麼做?
這將做到這一點:HTTP:
$('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();
}
});
試試;
$(li1).detach().insertAfter(li2);
或
$(li1).detach().insertBefore(li2);
請給您的答案添加一些解釋。 –
使用此代碼與jQuery: 此示例使用向上箭頭(38)。 要使用「向下」箭頭,用40代替38(在我的鉻,向下箭頭打開一些擴展功能):
$(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;
}
});
});
我已經根據我試圖改變li元素的無序列表 – Pavan
你看這個簡單的解決方案與document.activeElement嘗試: //codepen.io/sp90/pen/OPKbVG?editors=101 –
如果這些項目的順序很重要,那麼您應該使用有序列表,而不是無序列表以獲得語義標記 – unobf