您好,我需要使用像幻灯片放映一样的按钮切换图像,但不需要滑动,我已经尝试过一些东西,希望有人帮助我处理这种代码。我正在做这个
<img id="imageswitch" src="image/1.jpg" width="400" height="286" alt="photo1" />
<script>
var image = document.getElementById("imageswitch")
function switchImage(){
if(image.src = "image/1.jpg"){
image.src = "image/2.jpg";
}else if(image.src = "image/2.jpg"){
image.src = "image/3.jpg";
console.log("marche")
}else{
console.log("dont work man")
}
}
document.getElementById("boutonright").addEventListener("click", function () {
switchImage();
});
最佳答案
- 将图像路径放入数组中。
- 点击按钮操作您的数组:
var image = document.getElementById("imageswitch"),
images = [
"http://placehold.it/400x286/fb0/?text=1",
"http://placehold.it/400x286/0bf/?text=2",
"http://placehold.it/400x286/bf0/?text=3"
];
function switchImage(){
images.push( images.shift() );
image.src = images[0];
}
document.getElementById("boutonright").addEventListener("click", switchImage);
#imageswitch{height:180px;}
<button id="boutonright">NEXT</button><br>
<img id="imageswitch" src="http://placehold.it/400x286/fb0/?text=1" alt="photo1" />
如果您想同时拥有 PREV
和 NEXT
按钮:
var image = document.getElementById("imageswitch"),
images = [
"http://placehold.it/400x286/fb0/?text=1",
"http://placehold.it/400x286/0bf/?text=2",
"http://placehold.it/400x286/bf0/?text=3"
];
function switchImage(){
if(this.id==="next") images.push( images.shift() );
else /* id==="prev*/ images.unshift( images.pop() );
image.src = images[0];
}
document.getElementById("prev").addEventListener("click", switchImage);
document.getElementById("next").addEventListener("click", switchImage);
#imageswitch{height:180px;}
<button id="prev">PREV</button><button id="next">NEXT</button><br>
<img id="imageswitch" src="http://placehold.it/400x286/fb0/?text=1" alt="photo1" />
关于javascript - 旧的 javascript 幻灯片,没有幻灯片(onclick),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37016220/