如何重新排序页面刷新div?

时间:2018-03-20 05:04:36

标签: javascript php html css

每次页面刷新时如何重新排序div元素? 例如 -

<div class="class1"><a href="1.html">first</a></div>
<div class="class2"><a href="1.html">second</a></div>
<div class="class3"><a href="1.html">third</a></div>

我希望看到页面刷新的重新排序,如..当前的顺序是1-2-3 当我刷新它将成为2-3-1 .. 所以每次刷新页面都会改变div的位置?

4 个答案:

答案 0 :(得分:0)

由于您已标记了前端语言和后端语言,因此这是一个PHP解决方案:只需将所有元素放入数组并shuffle()

如果您的div更复杂,请将整个输出放在变量中并将该变量添加到数组中。或者,如果它们很简单(如您的示例)但需要更多信息,请使用关联数组并uksort()

$array = array(
    'first'  => array( 'class' => 'foo', 'href' => 'bar.html' ),
    'second' => array( 'class' => 'john', 'href' => 'doe.html' ),
    'third'  => array( 'class' => 'x', 'href' => 'y.html' ),
);

uksort( $array, function() { return rand() > rand(); } ); //This will mix them up.

foreach( $array as $item => $atts ){
    echo '<div class="'. $atts['class'] .'"><a href="'. $atts['href'] .'">'. $item .'</a></div>';
}

答案 1 :(得分:0)

在Javascript方面:将所有div放入容器中,然后:

const container = document.querySelector('#container');
const children = [...container.children];
children.forEach(child => child.remove());
const randomChildren = children.map((child) => ({ child, rand: Math.random() }));
randomChildren.sort((a, b) => b.rand - a.rand);
randomChildren.forEach(randomObj => container.appendChild(randomObj.child));

答案 2 :(得分:0)

您可以将JavaScript与数组shuffle一起使用

function shuffle(arra1) {
        var ctr = arra1.length,
            temp, index;
        while (ctr > 0) {
            index = Math.floor(Math.random() * ctr);
            ctr--;
            temp = arra1[ctr];
            arra1[ctr] = arra1[index];
            arra1[index] = temp;
        }
        return arra1;
    }
    var myArray = [
        '<div class="class1"><a href="1.html">first</a></div>',
        '<div class="class2"><a href="1.html">second</a></div>',
        '<div class="class3"><a href="1.html">third</a></div>'
    ];

    var randomHtml = shuffle(myArray).join("");
    document.getElementById("some").innerHTML = randomHtml;

答案 3 :(得分:0)

您可以使用以下脚本。它将在页面加载时随机播放div。

$(document).ready(function(){
function shuffle(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;
}

var arr = ['<div class="class1"><a href="1.html">first</a></div>', '<div class="class2"><a href="1.html">second</a></div>', '<div class="class3"><a href="1.html">third</a></div>'];
arr = shuffle(arr);
arr.map(function (k,v){
$(".div-wrap").append(k);
});
});

在你的html中添加一个div

<div class="div-wrap">

</div>

这是一个有效的例子......

https://jsfiddle.net/SmitRaval/2hhsaLh9/6/