PHP 和 JavaScript 的自动幻灯片放映

Automatic slideshow with PHP and JavaScript

基本上我已经制作了一个 PHP 程序,可以从文件夹中拍摄照片并将其放入图库中的 "slideshow" 中。 PHP 代码给出了从“1”开始的图像 ID,依此类推。

现在 JavaScript 我希望它每 2.5 秒自动切换一次图片。它实际上在我的 Firebug 脚本中按照我想要的方式运行,但在浏览器中没有任何反应。我已经在 HTML 正文底部发布了我的 JavaScript link,但没有帮助。

如有任何帮助,我们将不胜感激。

<div id="gallery" class="grey">
    <h3>Gallery</h3>
    <div id="slideshow">
        <?php
    $path = "./img/gallery";
    $all_files = scandir($path);
    $how_many = count($all_files);
        for ($i=2; $i<$how_many;$i++) {
            $kubi=$i - 1;
            echo "<img src=\"./img/gallery/$all_files[$i]\" id= \"$kubi\"/>";
        }
    ?>
    </div>
</div>

JavaScript代码:

var picture = document.getElementById("1");
var i = 0;
function rotateImages() {
    while (i < document.getElementById("slideshow").childNodes.length) {
        picture.style.display = "none";
            picture = picture.nextSibling;
            picture.style.display = "inline";
            i++;
    };
};

window.onload = function(){
document.getElementById("1").style.display = "inline";
setInterval(rotateImages(), 2500);
};  

发生的事情是总是使用相同的第一张元素图片,隐藏它然后显示第二张图片,它实际上并没有遍历所有图片。

在您的代码中,图片始终是第一个元素,next 始终是第二个元素。

另外,不应该是while循环,因为换一张图片调用一次回调,所以改成if,经过total个元素数后,重新回到第一张图片。

应该是:(Javascript)

var firstPicture = document.getElementById("1");
var picture = firstPicture ;
var i = 0;
function rotateImages() {
    // hide current element
    picture.style.display = "none";

    // choose who is the next element
    if (i >= document.getElementById("slideshow").childNodes.length) {
        i = 0;
        picture = firstPicture;
    } else {
        picture = picture.nextSibling;
    }

    // show the next element
    picture.style.display = "inline";
    i++;
};

window.onload = function(){
var curImg = document.getElementById("1").style.display = "inline";
setInterval(rotateImages, 2500);
};