How to swap element on screen with JavaScript

前端 未结 5 1575
你的背包
你的背包 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条回答
  •  萌比男神i
    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.dummy').each(function(index) {
       $(this).replaceWith(shuffled.splice(Math.random()*shuffled.length),1);
    });
    

提交回复
热议问题