Can I use jQuery to easily shift li elements up or down?

前端 未结 3 1856
小鲜肉
小鲜肉 2020-12-15 11:05

I have a menu like this:

    
  • Home
相关标签:
3条回答
  • 2020-12-15 11:39

    It's actually not that hard. JQuery almost gets you there by itself with the insertBefore and insertAfter methods.

    function moveUp($item) {
        $before = $item.prev();
        $item.insertBefore($before);
    }
    
    function moveDown($item) {
        $after = $item.next();
        $item.insertAfter($after);
    }
    

    You could use these like

    moveDown($('#menuAbout'));
    

    and the menuAbout item would move down.

    If you wanted to extend jQuery to include these methods, you would write it like this:

    $.fn.moveUp = function() {
        before = $(this).prev();
        $(this).insertBefore(before);
    };
    
    $.fn.moveDown = function() {
        after = $(this).next();
        $(this).insertAfter(after);
    };
    

    and now you can call the functions like

    $("#menuAbout").moveDown();
    
    0 讨论(0)
  • 2020-12-15 11:46

    You can also use display: flex on the parent then you can use order

    function reset()
    {
      jQuery("#a").css("order", 10);
      jQuery("#b").css("order", 20);
      jQuery("#c").css("order", 30);
    }
    
    function reorder1()
    {
      jQuery("#a").css("order", 30);
      jQuery("#b").css("order", 20);
      jQuery("#c").css("order", 10);
    }
    
    function reorder2()
    {
      jQuery("#a").css("order", 30);
      jQuery("#b").css("order", 10);
      jQuery("#c").css("order", 20);
    }
    #main { display: flex; }
    #a { color: red; }
    #b { color: blue; }
    #c { color: green; }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id="main">
        <div id="a">Foo</div>
        <div id="b">Bar</div>
        <div id="c">Baz</div>
    </div>
    
    <button onclick="reset()">Reset</button>
    <button onclick="reorder1()">Reorder 1</button>
    <button onclick="reorder2()">Reorder 2</button>

    0 讨论(0)
  • 2020-12-15 12:00

    No native prototypal methods, but you can make one easily:

    $.fn.moveDown = function() {
        return this.each(function() {
            var next = $(this).next();
            if ( next.length ) {
                $(next).after(this);
            } else {
              $(this).parent().append( this );
            }
        })
    }
    
    $('#menuAbout').moveDown().moveDown()
    

    This uses jQuery.prototype.after

    0 讨论(0)
提交回复
热议问题