How to swap element on screen with JavaScript

前端 未结 5 1530
你的背包
你的背包 2021-01-21 08:22

I have multiple \'li\' elements:

$(\".my_lis\")

with on the page I want to shuffle them around with JavaScript (I\'m using JQuery). How to do t

相关标签:
5条回答
  • 2021-01-21 09:09

    It's not too hard actually. The general idea is:

    1. Grab all the dom nodes
    2. Shuffle them
    3. Empty the <ul> and insert the shuffled nodes

    --

    var items = $('.my_list li').get();
    
    //edit (per comments): avoid confusion
    items = shuffle(items);
    
    $('.my_list').empty().append(items);
    

    Where shuffle() can be anything that shuffles the array, I prefer underscore.js but here is a vanilla JavaScript way of doing a shuffle on an Array:

    Just an example on shuffling ANY array

    function shuffle(items) {
    
        for(var index = 0, ln = items.length; index < ln; index++) {
            var item = items[index],
                swapIndex = ~~(Math.random() * ln),
                swapItem = items[swapIndex];
    
            //Swap places
            items.splice(swapIndex, 1, item);
            items.splice(index, 1, swapItem);
        }
    
        return items;
    }
    
    0 讨论(0)
  • 2021-01-21 09:14

    Maybe this plugin from James Padolsey helps you: http://css-tricks.com/snippets/jquery/shuffle-dom-elements/

    Simply use it like this: $('.my_lis').shuffle();

    Here's a demo: http://jsfiddle.net/y4kyw/ – Press run to shuffle the list again

    0 讨论(0)
  • 2021-01-21 09:17

    A reliable option is to insert a temporary dummy element after each element in the jQuery collection, then shuffle the current collection, and replace the elements in the dummy collection with elements from the shuffled list.

    When appending a DOM element to another place, the element is automatically removed from the previous place.

    Working demo: http://jsfiddle.net/ryEHm/2/

    Code:

    var $collection = $(".my_list li");
    var shuffled = [];
    $collection.each(function() {
        shuffled.push(this); //Push DOM element
    }).after('<span class="dummy"/>');
    
    $('span.dummy').each(function(index) {
       $(this).replaceWith(shuffled.splice(Math.random()*shuffled.length),1);
    });
    
    0 讨论(0)
  • 2021-01-21 09:18

    jsfiddle demo

    using

    jQuery plugin to randomly reorder child elements with callback — Gist

    to use: $(".my_lis").reorder();

    0 讨论(0)
  • 2021-01-21 09:20

    You can check out the jQuery Sortable plugin which has great examples and code walkthroughs/samples here:

    http://jqueryui.com/demos/sortable/

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