jQuery可排序上移/下移按钮

时间:2010-06-01 17:35:32

标签: jquery jquery-ui-sortable

我目前有一个完美的jQuery可排序列表。我能够移动'li'元素。但是,如何创建一个按钮将特定的“li”元素向上移动一个,将上面的元素向下移动(当然对于向下按钮则相反)?我环顾谷歌,发现很少。即使是链接也很棒!

谢谢!

3 个答案:

答案 0 :(得分:67)

如果您有以下HTML代码:

<button id="myButtonUp">myButtonTextForUp</button>
<button id="myButtonDown">myButtonTextForDown</button>
<ul>
  <li>line_1</li>
  <li>line_2</li>
  <li>line_3</li>
</ul>

我认为您已经准备好了标记每个li的内容,因此我假设标记为li的内容为markedLi;以下代码理论上应该向上或向下移动该元素(完全未经测试):

$('#myButtonUp').click(function(){
  var current = $('.markedLi');
  current.prev().before(current);
});
$('#myButtonDown').click(function(){
  var current = $('.markedLi');
  current.next().after(current);
});

答案 1 :(得分:39)

虽然Azatoth的答案很好,但是鲍比可能正在寻找动画,就像我一样。所以我编写了以下代码来使动画动画化:

function moveUp(item) {
    var prev = item.prev();
    if (prev.length == 0)
        return;
    prev.css('z-index', 999).css('position','relative').animate({ top: item.height() }, 250);
    item.css('z-index', 1000).css('position', 'relative').animate({ top: '-' + prev.height() }, 300, function () {
        prev.css('z-index', '').css('top', '').css('position', '');
        item.css('z-index', '').css('top', '').css('position', '');
        item.insertBefore(prev);
    });
}
function moveDown(item) {
    var next = item.next();
    if (next.length == 0)
        return;
    next.css('z-index', 999).css('position', 'relative').animate({ top: '-' + item.height() }, 250);
    item.css('z-index', 1000).css('position', 'relative').animate({ top: next.height() }, 300, function () {
        next.css('z-index', '').css('top', '').css('position', '');
        item.css('z-index', '').css('top', '').css('position', '');
        item.insertAfter(next);
    });
}

您可以在这里查看http://jsfiddle.net/maziar/P2XDc/

答案 2 :(得分:4)

根据@azatoth的回答,如果有人喜欢为每条记录设置按钮,他可以这样做(用可分类标签替换li标签)。

HTML:

Error Domain=com.facebook.Facebook.platform Code=102 "(null)" UserInfo={error_reason=The content you're trying to share includes a link that our security systems detected to be unsafe:

https://m.facebook.com/appcenter/smartsea?fbs=9909&fb_object_id=1684374595135519

Please remove this link to continue., error_description=An error occurred during publishing., app_id=xxxxxxxxxxxxxxxxxxxxx, error_code=102}

jQuery的:

<button class="my-button-up">Up</button>
<button class="my-button-down">Down</button>