我有这个脚本,我用来显示带有超链接的随机图像。任何人都可以告诉我如何适应它一次显示5个随机图像,最好不要重复两次相同的图像?
由于
<script language="JavaScript">
<!--
/*
Random Image Link Script- By JavaScript Kit(http://www.javascriptkit.com)
Over 200+ free JavaScripts here!
Updated: 00/04/25
*/
function random_imglink(){
var myimages=new Array()
//specify random images below. You can have as many as you wish
myimages[1]="data/adverts/ad1.png"
myimages[2]="data/adverts/ad2.png"
myimages[3]="data/adverts/ad3.png"
myimages[4]="data/adverts/ad4.png"
myimages[5]="data/adverts/ad5.png"
//specify corresponding links below
var imagelinks=new Array()
imagelinks[1]="http://www.javascriptkit.com"
imagelinks[2]="http://www.netscape.com"
imagelinks[3]="http://www.microsoft.com"
imagelinks[4]="http://www.dynamicdrive.com"
imagelinks[5]="http://www.freewarejava.com"
var ry=Math.floor(Math.random()*myimages.length)
if (ry==0)
ry=1
document.write('<a href='+'"'+imagelinks[ry]+'"'+'><img src="'+myimages[ry]+'" border=0></a>')
}
random_imglink()
//-->
</script>
答案 0 :(得分:0)
function random_imglink(){
var myimages=new Array();
...
var imagelinks=new Array();
...
var used = [];
var ry;
var howmany = 5;
for (var i = 1; i <= howmany; i++) {
ry=Math.ceil(Math.random()*myimages.length);
while(used.indexOf(ry)!=-1){
ry=Math.ceil(Math.random()*myimages.length);
}
used.push[ry];
document.write('<a href='+'"'+imagelinks[ry]+'"'+'><img src="'+myimages[ry]+'" border=0></a>')
}
}
这假设您将在阵列中放置的图像数量超过5个。
答案 1 :(得分:0)
相反随机并检查,如果您已经选择了图像,则可以将选择的图像移动到数组的末尾,并将随机变量减1。例如:
function random_imglink(select){
if (select > 5 ) {
// make it fail ...
}
//specify random images below. You can have as many as you wish
var myimages = new Array();
myimages[0]="data/adverts/ad1.png"
myimages[1]="data/adverts/ad2.png"
myimages[2]="data/adverts/ad3.png"
myimages[3]="data/adverts/ad4.png"
myimages[4]="data/adverts/ad5.png"
//specify corresponding links below
var imagelinks=new Array()
imagelinks[0]="http://www.javascriptkit.com"
imagelinks[1]="http://www.netscape.com"
imagelinks[2]="http://www.microsoft.com"
imagelinks[3]="http://www.dynamicdrive.com"
imagelinks[4]="http://www.freewarejava.com"
var size = myimages.length
for (var i=0;i<select;i++) {
var index = Math.floor(Math.random() * size);
document.write('<a href='+'"'+imagelinks[index]+'"'+'><img src="'+myimages[index]+'" border=0></a>');
var tmp = myimages[index];
myimages[index] = myimages[size - 1];
myimages[size - 1] = tmp;
tmp = imagelinks[index];
imagelinks[index] = imagelinks[size - 1];
imagelinks[size - 1] = tmp;
--size;
}
}
random_imglink(3);
答案 2 :(得分:0)
在一行代码中可能会出现类似情况而不创建函数:
<img src="https://www.example.com/images/image-<?php echo rand(1,7); ?>.jpg">
为了让它发挥作用,你需要为你的图像命名:image-1.jpg,image-2.jpg,image-3.jpg .... image-7.jpg,
当页面加载时,PHP rand()将回显一个随机数(在本例中为1到7之间的数字),完成URL并显示相应的图像。资料来源:https://jonbellah.com/load-random-images-with-php/