如何改变同级div,但保持子元素的顺序相同

时间:2016-04-06 15:28:17

标签: javascript jquery html css

如何随机重新排列div类shuffledv的顺序,但每次刷新页面时都会将ID保持为相同的顺序?

<div class="shuffledv">
<div id="2"></div>
<div id="3"></div>
<div id="1"></div>
</div>
<div class="shuffledv">
<div id="5"></div>
<div id="4"></div>
<div id="6"></div>
</div>
<div class="shuffledv">
<div id="9"></div>
<div id="8"></div>
<div id="7"></div>
</div>
<div class="shuffledv">
<div id="10"></div>
<div id="11"></div>
<div id="12"></div>
</div>

1 个答案:

答案 0 :(得分:1)

我认为这是你正在寻找的东西:

&#13;
&#13;
elems = $('.shuffledv');

elems = shuffle(elems); //shuffle all the elements.


for (i = 0; i < elems.length; i++) {

  $(elems[i]).appendTo($('.container')); //reinsert.
}

function shuffle(array) { //From COOLAJ86 at http://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array
  var currentIndex = array.length,
    temporaryValue, randomIndex;

  // While there remain elements to shuffle...
  while (0 !== currentIndex) {

    // Pick a remaining element...
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    // And swap it with the current element.
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }

  return array;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="container">


  <div class="shuffledv">
    first
    <div id="2"></div>
    <div id="3"></div>
    <div id="1"></div>
  </div>

  <div class="shuffledv">
    second
    <div id="5"></div>
    <div id="4"></div>
    <div id="6"></div>
  </div>
  <div class="shuffledv">
    third
    <div id="2"></div>
    <div id="3"></div>
    <div id="1"></div>
  </div>
  <div class="shuffledv">
    fourth
    <div id="5"></div>
    <div id="4"></div>
    <div id="6"></div>
  </div>
</div>
&#13;
&#13;
&#13;

每次运行时它都会随意乱扔。如果他们有一个容器,那就做得最好。