所以我用HTML / CSS / JS制作了这个小幻灯片,我想让它成为6个图像随机出现而不是1,2,3 ..更像是2,3,1 ..例如。任何帮助表示赞赏。非常感谢提前。
JS:
var imagecount = 1;
var total = 6;
function slide(x) {
var Image = document.getElementById('img');
imagecount = imagecount + x;
if(imagecount > total){imagecount = 1;}
if(imagecount < 1){imagecount = total;}
Image.src = "images/img"+ imagecount +".jpg";
ChangeText(imagecount);
}
window.setInterval(function slideA(x) {
var Image = document.getElementById('img');
imagecount = imagecount + 1;
if(imagecount > total){imagecount = 1;}
if(imagecount < 1){imagecount = total;}
Image.src = "images/img"+ imagecount +".jpg";
ChangeText(imagecount);
}, 3000);
function ChangeText(imgNum){
var allImagesAndText = {1: "Seltene römische Goldmünze", 2: "Römische Funde", 3: "Römische Wandmalerei", 4: "Tutanchamun", 5: "Cheops Pyramide", 6: "Ägyptische Malerei"};
document.getElementById("text1").innerHTML = allImagesAndText[imgNum];
}
CSS:
#container {
height: 450px;
width: 650px;
margin: 20px auto;
position: relative;
z-index: 1;
border: 10px solid #000;
border-radius: 10px;
}
#img {
height: 450px;
width: 650px;
}
#left_holder {
height: 450px;
width: 100px;
position: absolute;
left: 0px;
top: 0px;
}
#right_holder {
height: 450px;
width: 100px;
position: absolute;
right: 0px;
top: 0px;
}
.left {
height: 50px;
width: 50px;
position: absolute;
top: 40%;
left: 0px;
}
.right {
height: 50px;
width: 50px;
position: absolute;
top: 40%;
right: 0px;
}
#text1 {
position: absolute;
color: #fff;
font-size: 32px;
background-color: #000;
opacity: 0.5;
left: 37%;
z-index: 2;
}
HTML:
<div id="container">
<div id="text1">Text</div>
<img src="images/img1.jpg" id="img" />
<div id="left_holder">
<img onClick="slide(-1)" class="left" src="images/arrow_left.png" />
</div>
<div id="right_holder">
<img onClick="slide(1)" class="right" src="images/arrow_right.png" />
</div>
</div>
答案 0 :(得分:1)
您可以添加功能: -
function generateRandom(){
var x = Math.floor((Math.random() * 6) + 1); //generates random number from 1 to 6
return x;
}
然后调用此函数并正确使用
答案 1 :(得分:1)
您可以创建唯一的随机图像滑块。因此它不会多次重复图像(Soham的答案很好,但它会连续多次重复相同的图像)。
这样的事情:
var imagecount = 1;
var total = 6;
var uniqueRandoms = [];
function makeUniqueRandom() {
if (!uniqueRandoms.length) {
for (var i = imagecount; i <= total; i++) {
uniqueRandoms.push(i);
}
}
var index = Math.floor(Math.random() * uniqueRandoms.length);
var val = uniqueRandoms[index];
uniqueRandoms.splice(index, 1);
return val;
}
我使用this SO回答。
然后在您的代码中,只需在您需要的地方调用该函数。
仅针对autoslide的代码示例在https://jsfiddle.net/2gra4wk1/