【问题标题】:Automatic slideshow with PHP and JavaScript使用 PHP 和 JavaScript 的自动幻灯片
【发布时间】:2015-02-26 23:13:01
【问题描述】:

所以基本上我已经制作了一个 PHP 程序,它从文件夹中获取图片并将其放入画廊中的“幻灯片”中。 PHP 代码给出了从“1”开始的图像 id,依此类推。

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

任何帮助将不胜感激。

<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);
};  

【问题讨论】:

    标签: javascript php html slideshow


    【解决方案1】:

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

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

    另外,它不应该是一个while循环,因为回调被调用一次来改变一张图片,所以将它改为if,并在它通过总元素数时重置为第一张图片。

    应该是:(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);
    };
    

    【讨论】:

    • 我一直在脑海中浮现同样的想法,但认为自己已经摆脱了这种想法。你是绝对正确的。
    • 感谢您的代码和您的帮助。但是由于某种原因,代码只是在 window.onload 部分跳过。它实际上并没有运行里面的代码。你知道为什么会这样吗?
    • 更改 setInterval(rotateImages(), 2500);设置间隔(旋转图像,2500); .在函数后使用 () 会调用它,但需要发送函数对象本身。我还编辑了答案。
    • 没关系,我让它工作了。我刚刚在 setInterval 中的 rotateImages 之后删除了“()”。非常感谢您的帮助!
    • 大声笑,刚刚看到你的评论,完美的时机;)
    猜你喜欢
    • 2015-07-06
    • 2015-04-21
    • 2012-04-07
    • 2015-06-21
    • 2010-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多