多个图像阵列,单击一次按钮即可随机化图像
如您所见,我有三个数组,每个数组存储三个单独的图像.当前,您可以通过以下方式循环遍历每个阵列:每次单击鼠标以获取新图像.我想做的是合并随机!"按钮下方的按钮,要求每个阵列从其各自的阵列中更改为随机图像,并同时执行此操作.因此,说您单击随机!"然后每个数组将从其内部选择一个随机图像并显示它.
As you can see, I have three arrays which store three separate images each. Currently, you can cycle through each array by mouse-clicking the image to get a new image each time. What I want to do is incorporate the "Random!" button below to ask each array to change to a random image from within their respective array, and to do this simultaneously. So say you click "Random!" and then each array will pick a random image from within itself and display it.
我不确定该怎么做.有什么想法吗?
I'm not sure how to even go about doing this. Any thoughts?
<script type="text/javascript">
imgs=Array("pic1.jpg","pic2.jpg","pic3.jpg");
var x=0;
function change() {
document.getElementById("img").src=imgs[++x];
if (x==2) {
x=-1;
}
}
if (!imgs[x+1]) {
x=-1;
}
</script>
<img src="pic1.jpg" id="img" onmousedown="change()" style="cursor: pointer;">
<img src="" id="img" alt="" onmousedown="change()"><br>
<!-- /slider -->
<script type="text/javascript">
imgs1=Array("pic4.jpg","pic5.jpg","pic6.jpg");
var x1=0;
function change1() {
document.getElementById("img1").src=imgs1[++x1];
if (x1==2) {
x1=-1;
}
}
if (!imgs1[x1+1]) {
x1=-1;
}
</script>
<img src="pic4.jpg" id="img1" onmousedown="change1()" style="cursor: pointer;">
<img src="" id="img1" alt="" onmousedown="change1()"><br>
<!-- /slider1 -->
<script type="text/javascript">
imgs2=Array("pic7.jpg","pic8.jpg","pic9.jpg");
var x2=0;
function change2() {
document.getElementById("img2").src=imgs2[++x2];
if (x2==2) {
x2=-1;
}
}
if (!imgs2[x2+1]) {
x2=-1;
}
</script>
<img src="pic7.jpg" id="img2" onmousedown="change2()" style="cursor: pointer;">
<img src="" id="img2" alt="" onmousedown="change2()"><br>
<!-- /slider2 -->
<a href="#" data-role="button">Random!</a>
您可以使用randomizer函数选择随机数组索引:
You can use a randomiser function to pick a random array index:
function getRandomIndex(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
因此,您可以在更改功能中执行以下操作:
So in your change functions you can then do:
document.getElementById("img1").src=imgs1[getRandomIndex(0,imgs1.length - 1)];