我是 JS 新手,我无法让这个脚本工作。我想我知道问题是什么,但不知道如何解决。
//images
const image1 = document.getElementById('image1');
const image2 = document.getElementById('image2');
const images = [image1, image2];
//buttons
const suivant = document.getElementById('button1');
const precedent = document.getElementById('button2');
//change images
suivant.onclick = function() {
i = 0;
if (i = 0, true) {
i++
images[i];
} else if (images[1]) {
i--
images[i];
}
};
<link href="https://fonts.googleapis.com/css?family=Open+Sans+Condensed:300|Sonsie+One" rel="stylesheet" type="text/css">
<div style="width: 60%; margin: auto;">
<div id="exemple1" name="slide" style="display: flex;">
<img id="image1" class="présente" name="slide" src="https://lemag.nikonclub.fr/wp-content/uploads/2017/07/08.jpg" height="500" alt="" />
<img id="image2" class="présente" name="slide" src="https://www.travelercar.com/wp-content/uploads/2016/04/4a36e314016aa914f203ea6b7d579dc6_large.jpeg" height="500" alt="" />
</div>
</div>
<div id="bouton" style='display: flex'>
<button id="button1" style="margin-right: 15px;">suivant</button>
<button id="button2">précédent</button>
</div>
最佳答案
onClick 事件处理程序似乎没有多大意义。 我希望您想要的是这样的:
//images
const image1 = document.getElementById('image1');
const image2 = document.getElementById('image2');
const images = [image1,image2];
//buttons
const suivant = document.getElementById('button1');
const precedent = document.getElementById('button2');
//change images
images[0].style.display ="block";
images[1].style.display ="none";
suivant.onclick = function(){
// Loop through each image and check if it's hidden or shown
images.forEach((image) => {
// If hidden -> make it display block
if (image.style.display === "none") image.style.display = "block";
// Else if shown -> make it display none
else image.style.display = "none";
});
};
如果您想让此功能适用于两个以上的图像:
//images
const image1 = document.getElementById('image1');
const image2 = document.getElementById('image2');
const image3 = document.getElementById('image3');
const images = [image1,image2, image3];
// Store the index of the currently active image.
let activeImage = 0;
//buttons
const next = document.getElementById('button1');
const prev = document.getElementById('button2');
//change images
images[0].style.display ="block";
images[1].style.display ="none";
next.onclick = function(){
// Hide currently active index
images[activeImage].style.display = "none";
// Show the index that's next up
images[++activeImage + 1].style.display = "block";
};
prev.onclick = function(){
// Hide currently active index
images[activeImage].style.display = "none";
// Show the index that's next up
images[activeImage - 1].style.display = "block";
};
关于javascript - 如何修复这个 JavaScript slider 代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58934217/