jQuery Sortable Move UP/DOWN Button

北城余情 提交于 2019-12-17 22:15:14

问题


I currently have a jQuery sortable list working perfectly. I am able to move the 'li' elements around. However, how can I make a button to move a specific 'li' element up by one and the one above to move down (and of course the opposite for a down button)? I have looked around google and found very little. Even a link would be fantastic!

Thanks!


回答1:


If you have following html code:

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

I assume you have allready something to mark each lis, so following I assume the marked lihas the class markedLi; Following code should in theory move that element up or down (totally untested off course):

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



回答2:


Although the answer by Azatoth works fine, bobby might be looking for an animation, like I did. so I wrote the following code to make the movement animated:

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);
    });
}

you can take a look in here http://jsfiddle.net/maziar/P2XDc/




回答3:


Based on @azatoth answer, if someone like to have the buttons for every record he can do it in this way (replace the li tag with your Sortable tag).

HTML:

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

jQuery:

$('.my-button-up').click(function(){
    var current = $(this).closest('li');
    current.prev().before(current);
});
$('.my-button-down').click(function(){
    var current = $(this).closest('li');
    current.next().after(current);
});


来源:https://stackoverflow.com/questions/2951941/jquery-sortable-move-up-down-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!