1

同じ「pic」クラスを持つ複数の要素があり、それぞれにページ上の位置を制御する独自のインクリメント クラス (pos_1、pos2、pos_3 など) があります。

各要素に「アニメーション」クラスが追加されるようにループを作成したいのですが、要素をランダムな順序でループしたいです。

JS でハードコードされた要素の配列を使用したくない場合は、どうすればよいでしょうか。

私のhtml要素の例は次のとおりです。

<div class="pic pos_1">
    ...
</div>

<div class="pic pos_2">
    ...
</div>

<div class="pic pos_3">
    ...
</div>
4

3 に答える 3

2

試す

var arr = $('.pic').get();
while(arr.length){
    var el = arr.splice(Math.floor(Math.random() * arr.length), 1);
    $(el).addClass('animate')
}

デモ:フィドル

アップデート

var arr = $('.pic').get();

function random(arr) {
    if (!arr.length) {
        return;
    }
    var el = arr.splice(Math.floor(Math.random() * arr.length), 1);
    $(el).addClass('animate');
    setTimeout(function () {
        random(arr);
    }, 1000 + Math.floor(Math.random() * 1000))
}
random(arr);

デモ:フィドル

于 2013-10-14T09:56:01.873 に答える
0

ページ内の画像の総数を取得し、表示する画像のインデックスをランダムに選択します

//Remove 'animate' class from all pictures.
$('.pic').removeClass('animate');
//Count of pictures in your page.
var picCount = $('.pic').length();      
//Random index of picture.
var picIndexToShow = Math.floor(Math.random() * picCount);

//Random picture from page
var randomPic = $($('.pic')[picIndexToShow]);
//Add 'animate' class
randomPic.addClass('animate');
于 2013-10-14T09:59:55.240 に答える