15 個の div 要素を含むページがあります。少なくとも 36 個の画像の配列からランダムな画像を各 div に入力する必要があります。次に、画像をランダムな間隔で回転させる必要があります。この部分は、 Choose image URL from large array, insert into random DIV on page, cycle で提供されているソリューションを使用しています。
画像が既にページに表示されている場合、配列から画像を呼び出せないようにコードを改善したいと思います。これは私が立ち往生しているものです。
これはこれまでの私のコードです。
function random_int(max) {
return Math.floor(Math.random() * max);
}
$(document).ready(function() {
var images = ['http://placekitten.com/159/159', 'http://placekitten.com/160/160', 'http://placekitten.com/161/161', 'http://placekitten.com/162/162', 'http://placekitten.com/163/163', 'http://placekitten.com/164/164', 'http://placekitten.com/165/165', 'http://placekitten.com/166/166', 'http://placekitten.com/167/167', 'http://placekitten.com/168/168', 'http://placekitten.com/169/169', 'http://placekitten.com/170/170', 'http://placekitten.com/171/171', 'http://placekitten.com/172/172', 'http://placekitten.com/173/173', 'http://placekitten.com/174/174', 'http://placekitten.com/175/175', 'http://placekitten.com/176/176', 'http://placekitten.com/177/177', 'http://placekitten.com/178/178', 'http://placekitten.com/179/179'];
var $divs = $('div.projectItem');
$divs.each(function() {
$('<img width="100%" />', {
src: 'http://placekitten.com/180/180',
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);
});
私が達成したいもう 1 つのことは、ページが最初に読み込まれたときに各 div に画像を配置することです。jsfiddle の例では、div が空であり、ページが読み込まれた後もしばらくそのままであることがわかります。各 div に最初の img タグを含めようとしましたが、ランダムな画像が読み込まれると、最初の画像が置き換えられず、各 div に 2 つの画像が含まれてしまいます。のせいだと思います.appendTo(this);
。これを次のように変更する必要があると思いますreplaceChild
か?
初めてポスターを作成する方や JS の初心者の方は、どんな支援でも歓迎します。