我需要创建一个显示图片的网页,该图片将在2秒内替换为另一张图片。阵列内总共3张图像。但是,当显示当前图像时,我的随机函数应该只允许从阵列内的其余图像中进行选择,并在2秒后替换当前图像。
我能够对整个数组中的图像进行随机化处理,但不能对其余图像进行随机化处理。在这方面需要帮助。谢谢。
$(function(){
//prepare Your data array with img urls
var dataArray=new Array();
dataArray[0]="cat2.jpg";
dataArray[1]="cat3.jpg";
dataArray[2]="cat1.jpg";
//start with id=0 after 2 seconds
var thisId=0;
window.setInterval(function(){
var randomNum = Math.floor(Math.random() * dataArray.length);
document.getElementById("thisImg").src = dataArray[randomNum];
},2000);
});
<!DOCTYPE html>
<html>
<head>
<title>Task 2</title>
<!-- calling external js file -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<img id="thisImg" alt="img" src="cat1.jpg"/>
<script src ="Task2.js"></script>
</body>
</html>
答案 0 :(得分:2)
尝试这种方法,只是在选择下一个图像并随机选择之前对图像进行过滤。
const numbers = [1,2,3,4,5]
let currentNumber = 1;
const run = (numbers, cn) => {
setInterval(() => {
const filtered = numbers.filter(num => num !== cn);
const random = filtered[Math.floor(Math.random() * filtered.length)]
// here set background to random
console.log(`
Current: ${cn}
Filtered: ${filtered}
Next: ${random}
`)
cn = random;
}, 3000)
}
run(numbers, currentNumber)
答案 1 :(得分:0)
从数组中拼接使用的图像源
$(function(){
//prepare Your data array with img urls
var dataArray=new Array();
dataArray[0]="cat2.jpg";
dataArray[1]="cat3.jpg";
dataArray[2]="cat1.jpg";
//start with id=0 after 2 seconds
var thisId=0;
var a=window.setInterval(function(){
var randomNum = Math.floor(Math.random() * dataArray.length);
if(typeof dataArray[randomNum]==="undefined")
{ clearInterval(a);}
document.getElementById("thisImg").src = dataArray[randomNum];
dataArray.splice(randomNum,1);
},2000);
});
<!DOCTYPE html>
<html>
<head>
<title>Task 2</title>
<!-- calling external js file -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<img id="thisImg" alt="img" src="cat1.jpg"/>
<script src ="Task2.js"></script>
</body>
</html>
答案 2 :(得分:0)
我使用thisId
作为当前图像ID的占位符。每次生成随机数时,都可以将其与thisId
进行比较,如果等于thisId
,则可以对其进行更改。然后再次将thisId=randomNum
设置为下一个循环。
$(function(){
var thisId=0;
//prepare Your data array with img urls
var dataArray=new Array();
dataArray[0]="cat2.jpg";
dataArray[1]="cat3.jpg";
dataArray[2]="cat1.jpg";
window.setInterval(function(){
var randomNum = Math.floor(Math.random() * dataArray.length);
if (thisId==randomNum){randomNum++;};
if (randomNum==3){randomNum=0};
thisId=randomNum;
document.getElementById("thisImg").src = dataArray[randomNum];
},2000);
});