1

ちょっと変わったリクエスト。300 までの画像 URL と 27div秒があります。それぞれdivに がありid="img1"1は 1 から (ご想像のとおり) 27 までの数字で、class="imageblock"(一般的なスタイリング用) です。

これらdivの のそれぞれに を挿入したいと思い<img src="http://foo.bar/img.jpg" width="640">ます。ここで、URL は約 300 のリストからランダムに選択され、いずれかの にランダムに挿入されdivます。27divのそれぞれに、300 のオプションから選択した独自のイメージが必要です。

さらに、これらのイメージは循環する必要があります。5 秒ごとに、ページ上の 1 つのランダムな画像 URL を別のランダムな URL に置き換えたいと考えています。

これは私がちょっとした助けを借りてまとめようとした(ひどい)コードですが、私はjavascriptが役に立たず、これを機能させることができません:

<script type="text/javascript">     
    $('document').ready(function() {        
                    var divs = $('div');

                        $("div").each(function() {
                          $(this).html("<img src='http://foo.bar/img1.jpg'alt='"+$(this).attr("id")+"'/>");         
                        });  

                        var imageChanger = setInterval(function() {switchImage()}, 500);


                        function switchImage() {
                         var new_image_url = [ 'http://foo.bar/anotherimg.jpg', 'http://bar.foo/image.jpg', 'http://foo.bar/imgremote.jpg'];

                            var random_div = Math.floor(Math.random() * $('div').length);
                            var random_img = Math.floor(Math.random() * $(new_image_url.length);

                          $("div:nth-child("+random_div+")").html('<img src="('+random_img+')" width="640">)');            

                        }
    });
    </script>

リモート画像は一般的なパターンに従っていないため、random_img変数が機能しないことに注意してください。

どんな助けでも大歓迎です。

4

1 に答える 1

5

配列からランダムな要素を選択するには、これを使用できます。

var random_div = divs[Math.floor(Math.random() * divs.length)];
var random_img = new_image_url[Math.floor(Math.random() * new_image_url.length)];

コードのもう少し効率的なバージョンを次に示します。

function random_int(max) {
    return Math.floor(Math.random() * max);
}

$(document).ready(function() {
    var images = ['http://foo.bar/anotherimg.jpg', 'http://bar.foo/image.jpg', 'http://foo.bar/imgremote.jpg'];
    var $divs = $('div');

    $divs.each(function() {
        $('<img />', {
            src: 'http://foo.bar/img1.jpg',
            alt: this.id
        }).appendTo(this);
    });

    function switchImage() {
        var $div = $divs.eq(random_int($divs.length));
        var image = images[random_int(images.length)];

        $div.find('img').attr('src', image);
    }

    var imageChanger = setInterval(switchImage, 500);
});
于 2012-09-29T04:46:09.550 に答える