我需要制作带幻灯片的HTML页面。幻灯片中的照片必须每2秒更换一次。在显示当前图像0.5秒后,应在图像上显示文本。这应该不使用jQuery或其他库,只需javascript函数。这就是我现在所拥有的,但它无法正常工作。
var imageIndex = 0;
var textIndex = 0;
displayImage();
displayText();
function displayImage() {
var i;
var x = document.getElementsByClassName("mySlides");
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
imageIndex++;
if (imageIndex > x.length) {imageIndex = 1}
x[imageIndex-1].style.display = "block";
setTimeout(displayImage, 2000); // Change image every 2 seconds
}
function displayText() {
var i;
var x = document.getElementsByClassName("text");
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
textIndex++;
if (textIndex > x.length) {textIndex = 1}
x[textIndex-1].style.display = "block";
setTimeout(displayText, 2500);
}
<div class="container">
<div class="mySlides">
<img src="Images/slide1.jpg">
<div class="text">Yunnan, China</div>
</div>
<div class="mySlides">
<img src="Images/slide2.jpg">
<div class="text">Namib Desert, Africa</div>
</div>
<div class="mySlides">
<img src="Images/slide3.jpg">
<div class="text">Rapeseed fields in Luoping, China</div>
</div>
<div class="mySlides">
<img src="Images/slide4.jpg">
<div class="text">Colorado, USA</div>
</div>
</div>
答案 0 :(得分:1)
您似乎每2500秒调用一次displayText,这会使您的文字每次显示额外超过500毫秒
例如,
img 1 = 2000
text 1 = 2500 (+500)
img 2 = 4000
text 2 = 5000 (+1000)
img 3 = 6000
text 3 = 7500 (+1500)
等
你需要在图像淡入后500ms调用displayText()函数。
function displayImage() {
var i;
var x = document.getElementsByClassName("mySlides");
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
imageIndex++;
if (imageIndex > x.length) {imageIndex = 1}
x[imageIndex-1].style.display = "block";
setTimeout(displayText, 500);
setTimeout(displayImage, 2000); // Change image every 2 seconds
}
function displayText() {
var i;
var x = document.getElementsByClassName("text");
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
textIndex++;
if (textIndex > x.length) {textIndex = 1}
x[textIndex-1].style.display = "block";
}
这应该在每次图像更改时运行您的功能,但仅在半秒后运行。
答案 1 :(得分:0)
它不起作用,因为显示图像和显示文字在不同时间点火?这应该有所帮助:
var imageIndex = 0;
var textIndex = 0;
var timeText = 0;
setInterval(displayImage, 2000);
function displayImage() {
if(timeText !== 0) { //just in case displayImage() takes more than 2000 miliseconds.
clearTimeout(timeText);
}
var i;
var x = document.getElementsByClassName("mySlides");
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
imageIndex++;
if (imageIndex > x.length) {imageIndex = 1}
x[imageIndex-1].style.display = "block";
timeText = setTimeout(displayText, 500);
}
function displayText() {
var i;
var x = document.getElementsByClassName("text");
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
textIndex++;
if (textIndex > x.length) {textIndex = 1}
x[textIndex-1].style.display = "block";
}