幻灯片中最多只能显示 4 张图片,上一个按钮的作用相同
Java:
imgArray = new Array(10);
imgArray[0] = new Image;
imgArray[0].src = "Euclid.png";
imgArray[1] = new Image;
imgArray[1].src = "Pythagoras.png";
imgArray[2] = new Image;
imgArray[2].src = "Fibonacci.png";
imgArray[3] = new Image;
imgArray[3].src = "Descartes.png";
imgArray[4] = new Image;
imgArray[4].src = "Fermat.png";
imgArray[5] = new Image;
imgArray[5].src = "Pascal.png";
imgArray[6] = new Image;
imgArray[6].src = "Newton.png";
imgArray[7] = new Image;
imgArray[7].src = "Leibniz.png";
imgArray[8] = new Image;
imgArray[8].src = "Euler.png";
imgArray[9] = new Image;
imgArray[9].src = "Gauss.jpg";
index = 0;
function doPrevious()
{
if (index > 0)
{
index--;
document.slideshow.src = imgArray[index].src;
}
return;
}
function doNext()
{
if (index < 9)
{
index++;
document.slideshow.src = imgArray[index].src;
}
return;
}
<!DOCTYPE HTML>
<html lang = "en">
<head>
<meta charset = "UTF-8">
<title>Mathmeticians Slide Show</title>
<script src = "MathSlide.js"></script>
</head>
<body>
<noscript>JavaScript Not Enabled!</noscript>
<h1>My Mathmetician Slide Show!!!</h1>
<br>
<img src="Euclid.png" name = "slideshow" height = "500" width = "300">
<a href = "javascript:doPrevious()">Previous</a> <a href = "javascript:doNext()">Next</a>
</body>
</html>
抱歉,我无法包含数学家的图像。 幻灯片只显示笛卡尔,仅此而已
基本上我有一个包含所有 10 张图片、html 文件和 JavaScript 文件的文件夹。我认为代码会做的是从 html 文件中搜索以查找 JS 文件,尽管我想我错了
您逻辑中的问题是因为您使用了不存在的
document.slideshow
。您需要在 DOM 中定位您的 img
元素,例如使用 querySelector()
或 getElementById()
等方法,然后您可以更新其 src
以匹配给定的索引。
这是一个工作示例。另请注意,我对逻辑进行了一些修改,以更好地满足当前的最佳实践 - 例如。避免将 JS 方法引用放在
href
或 onclick
属性中,并简化逻辑以将 index
保持在数组范围内。请注意,我还设置了图像的 alt
,以便您可以看到它们正在更改。
const slideshow = document.querySelector('#slideshow');
const prev = document.querySelector('#prev');
const next = document.querySelector('#next');
prev.addEventListener('click', e => {
e.preventDefault();
index = Math.max(--index, 0);
slideshow.src = imgArray[index].src;
});
next.addEventListener('click', e => {
e.preventDefault();
index = Math.min(++index, imgArray.length -1);
slideshow.src = imgArray[index].src;
slideshow.alt = imgArray[index].src;
})
let index = 0;
const imgArray = [];
imgArray[0] = new Image;
imgArray[0].src = "Euclid.png";
imgArray[1] = new Image;
imgArray[1].src = "Pythagoras.png";
imgArray[2] = new Image;
imgArray[2].src = "Fibonacci.png";
imgArray[3] = new Image;
imgArray[3].src = "Descartes.png";
imgArray[4] = new Image;
imgArray[4].src = "Fermat.png";
imgArray[5] = new Image;
imgArray[5].src = "Pascal.png";
imgArray[6] = new Image;
imgArray[6].src = "Newton.png";
imgArray[7] = new Image;
imgArray[7].src = "Leibniz.png";
imgArray[8] = new Image;
imgArray[8].src = "Euler.png";
imgArray[9] = new Image;
imgArray[9].src = "Gauss.jpg";
#slideshow {
height: 100px;
width: 300px;
}
<h1>My Mathmetician Slide Show!!!</h1>
<img src="Euclid.png" id="slideshow" />
<a href="#" id="prev">Previous</a>
<a href="#" id="next">Next</a>