【发布时间】:2011-04-27 19:05:29
【问题描述】:
我正在为摄影师使用网站主页上的脚本,该脚本显示从数组中随机选择的图像。我发现了两个执行此功能的不同脚本。我想知道哪个脚本更可取,以及它是否编写正确或可以改进。我想知道是否可以包含一个函数,该函数会阻止同一图像加载两次,直到数组中的所有图像都被使用。感谢您的观看。
版本 1
<script type="text/javascript">
<!--
var theImages = new Array()
theImages[1] = 'portrait/fpo/01.jpg'
theImages[2] = 'portrait/fpo/02.jpg'
theImages[3] = 'portrait/fpo/03.jpg'
theImages[4] = 'portrait/fpo/04.jpg'
theImages[5] = 'portrait/fpo/05.jpg'
theImages[6] = 'portrait/fpo/06.jpg'
theImages[7] = 'portrait/fpo/07.jpg'
theImages[8] = 'portrait/fpo/08.jpg'
theImages[9] = 'portrait/fpo/09.jpg'
theImages[10] = 'portrait/fpo/10.jpg'
var j = 0
var p = theImages.length;
var preBuffer = new Array()
for (i = 0; i < p; i++){
preBuffer[i] = new Image()
preBuffer[i].src = theImages[i]
}
var whichImage = Math.round(Math.random()*(p-1));
function showImage(){
document.write('<img src="images/'+theImages[whichImage]+'">');
}
// -->
</script>
<table cellpadding="0" cellspacing="0" border="0" height="100%" width="100%">
<tr valign="middle"><td align="center">
<a href="index.html"><script type="text/javascript">showImage();</script></a>
</td></tr>
</table>
第 2 版
<script type="text/javascript">
<!--
var ic = 11; // Number of alternative images
var xoxo = new Array(ic); // Array to hold filenames
xoxo[0] = "images/portrait/fpo/01.jpg"
xoxo[1] = "images/portrait/fpo/02.jpg"
xoxo[2] = "images/portrait/fpo/03.jpg"
xoxo[3] = "images/portrait/fpo/04.jpg"
xoxo[4] = "images/portrait/fpo/05.jpg"
xoxo[5] = "images/portrait/fpo/06.jpg"
xoxo[6] = "images/portrait/fpo/07.jpg"
xoxo[7] = "images/portrait/fpo/08.jpg"
xoxo[8] = "images/portrait/fpo/09.jpg"
xoxo[9] = "images/portrait/fpo/10.jpg"
xoxo[10] = "images/portrait/fpo/11.jpg"
function pickRandom(range) {
if (Math.random)
return Math.round(Math.random() * (range-1));
else {
var now = new Date();
return (now.getTime() / 1000) % range;
}
}
// Write out an IMG tag, using a randomly-chosen image name.
var choice = pickRandom(ic);
// -->
</script>
<table cellpadding="0" cellspacing="0" border="0" height="100%" width="100%">
<tr valign="middle"><td align="center">
<a href="index-alternate.html"><script type="text/javascript">document.writeln('<img src="'+xoxo[choice]+'" >');</script></a>
</td></tr>
</table>
【问题讨论】:
-
您在第一个版本中丢失了一张照片,仅供参考。我会选择 2。1 是预先加载所有图像(如果您在页面加载时更改图像,则更有用)。所以它使用更多的带宽,会使你的页面加载速度变慢。
标签: javascript