我有一个包含4张图片的页面。我想在每次查看页面时从一系列图像中随机选择这些图像。
图像还需要链接到特定页面(取决于显示的图像)。 例如:
HTML:
<div class="thankyou_wrapper">
<div class="thankyou">
<div class="socialphoto_container">
<div class="socialphoto"><a href="page_082.html" target="_self"><img src="images/image_01.jpg" width="220" height="220" /></a></div>
<div class="socialphoto"><a href="page_128.html" target="_self"><img src="images/image_05.jpg" width="220" height="220" /></a></div>
<div class="socialphoto"><a href="page_852.html" target="_self"><img src="images/image_08.jpg" width="220" height="220" /></a></div>
<div class="socialphoto"><a href="page_685.html" target="_self"><img src="images/image_04.jpg" width="220" height="220" /></a></div>
</div>
</div>
</div>
CSS:
.thankyou_wrapper {
width: 100%;
background-color: #FFF;
}
.thankyou {
margin: auto;
width: 940px;
min-height: 216px;
overflow: hidden;
padding-top: 20px;
padding-bottom: 20px;
}
.socialphoto_container {
width: 940px;
height: 230px;
}
.socialphoto {
width: 240px;
height: 220px;
margin-right: 0px;
float: left;
}
.socialphoto:last-child {
width: 220px;
}
有什么想法吗?
答案 0 :(得分:4)
可以通过创建可能图像的数组,对阵列进行洗牌,然后抓取前4个图像并附加到div来完成:
// randomize array function
Array.prototype.shuffle = function() {
var i = this.length, j, temp;
if ( i == 0 ) return this;
while ( --i ) {
j = Math.floor( Math.random() * ( i + 1 ) );
temp = this[i];
this[i] = this[j];
this[j] = temp;
}
return this;
}
// declare image data as array of objects
var images = [
{ src : 'images/image_01.jpg', href : 'page_082.html' },
{ src : 'images/image_02.jpg', href : 'page_083.html' },
{ src : 'images/image_03.jpg', href : 'page_084.html' },
{ src : 'images/image_04.jpg', href : 'page_085.html' },
{ src : 'images/image_05.jpg', href : 'page_086.html' },
{ src : 'images/image_06.jpg', href : 'page_087.html' }
];
$(document).ready(function(){
var img, anchor, div;
var cont = $('.socialphoto_container');
cont.children().remove();
images.shuffle();
for(var i=0; i<4; i++){
img = $('<img />', { src : images[i].src });
anchor = $('<a></a>', { href : images[i].href, target : '_self' });
div = $('<div></div>', { class : 'socialphoto' });
anchor.append(img);
div.append(anchor);
cont.append(div);
}
});
Array.shuffle()
是Fisher-Yates算法,取自here。