Any way to shuffle content in multiple div elements

前端 未结 8 1130
鱼传尺愫
鱼传尺愫 2020-12-31 23:32

I\'m relatively new to Javascript and was wondering if there\'s a quick way to shuffle content that is contained in multiple

tags. For example

8条回答
  •  情书的邮戳
    2021-01-01 00:08

    For your HTML, the short answer to your question is:

    function shuffle_content() {
     var divA = new Array(3);
     for(var i=0; i < 3; i++) {
      divA[i] = document.getElementById('d'+(i+1));
      document.body.removeChild(divA[i]);
     }
     while (divA.length > 0)
      document.body.appendChild(divA.splice(Math.floor(Math.random() * divA.length),1)[0]);
    }
    

    To get there I wrote the following, which I think works better:

    
    
    Card0
    Card1
    Card2
    Card3
    Card4
    Card5
    Card6
    Card7
    Card8
    Card9

    I was trying to pack down that last while statement to:

        while (mDivCardsArray.length > 0) {
            divCards.appendChild(
                mDivCardsArray.splice(
                    Math.floor(Math.random() * mDivCardsArray.length)
                    ,1)[0]
            );
        }
    

    but this is pretty hard to read and prone to error.

    Going with jQuery or Prototype you could follow the same basic structure and get the result you're looking for.

    Personally, I think it looks even better if you add 2 more divs to the cards stack, expand the divCardsArray, insert the following style block, and add this code right after the divCardsArray definition.

    
    ...
    
    ...
    
    CardA
    CardB
    ... var colorCardsArray = new Array( '#f00', '#f80', '#ff0', '#8f0', '#0f0', '#0f8', '#0ff', '#08f', '#00f', '#80f', '#f0f', '#f08' ); for(var i=0;i

提交回复
热议问题