使用JavaScript从图像切换为随机图像onclick [英] switch from image to random image onclick with JavaScript
问题描述
我正在尝试构建类似于幻灯片的内容,其中有图像,当您单击它时,它会随机替换为我的一系列图像中的图像.我首先尝试使用简单的html,但是图像不会随机切换.因此,我进行了研究,发现可以用Javascript中的数组来完成.我只是不太了解javascript ...
I'm trying to build something that would resemble a slide show, where you have an image and when you click on it, it is replaced by another randomly in my series of images. I first tried with simple html, but of course the images don't switch randomly. So I did my research and found that it could be done with an array in Javascript. I just don't really know a lot about javascript…
这是我可以找到的,但是它不起作用,我确定其中有一个愚蠢的错误,我看不到:
This is what I could find but it doesn't work, I'm sure there is a stupid mistake in there that I can't see:
这是我的javascript
this is my javascript
function pickimg2() {
var imagenumber = 2 ;
var randomnumber = Math.random();
var rand1 = Math.round((imagenumber-1) * randomnumber) + 1;
myImages1 = new Array();
myImages1[1] = "img_01.gif";
myImages1[2] = "img_02.gif";
myImages1[3] = "img_03.gif";
myImages1[4] = "img_04.gif";
myImages1[5] = "img_05.gif";
myImages1[6] = "img_06.gif";
myImages1[7] = "img_07.gif";
myImages1[8] = "img_08.gif";
myImages1[9] = "img_09.gif";
var image = images[rand1];
document.randimg.src = "myImages1";
}
有我的html
<!DOCTYPE html>
<html>
<head>
<title>mur</title>
<link rel="stylesheet" href="style.css">
<link rel="JavaScript" href="script.js">
</head>
<body onLoad="pickimg2">
<div class="fenetre">
<a href="" onClick="pickimg();return false;"><img src="img_01.gif" name="randimg" border=0></a>
</div>
</body>
</html>
如果有人有其他解决方案,我愿意接受它!
If someone has another solution I'm open to it!
推荐答案
修复您提到的RamenChef之类的脚本链接:
Fix your script link like RamenChef mentioned:
<script type="text/javascript" src="script.js"></script>
这是更新的代码,请查看console.log以查看请求的其他图像URL.
Here's the updated code, check console.log to see the different image urls getting requested.
var myImages1 = new Array();
myImages1.push("img_01.gif");
myImages1.push("img_02.gif");
myImages1.push("img_03.gif");
myImages1.push("img_04.gif");
myImages1.push("img_05.gif");
myImages1.push("img_06.gif");
myImages1.push("img_07.gif");
myImages1.push("img_08.gif");
myImages1.push("img_09.gif");
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function pickimg2() {
document.randimg.src = myImages1[getRandomInt(0, myImages1.length - 1)];
}
<div class="fenetre">
<a href="#" onClick="pickimg2();return false;">
<img src="img_01.gif" name="randimg" border=0>
</a>
</div>
这篇关于使用JavaScript从图像切换为随机图像onclick的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!