简体   繁体   English

使用PHP和JavaScript进行自动幻灯片放映

[英]Automatic slideshow with PHP and JavaScript

So basically i have made a PHP program that takes pictures from a folder and puts it into the "slideshow" in Gallery. 因此,基本上我已经制作了一个PHP程序,该程序从文件夹中拍摄图片并将其放入Gallery中的“幻灯片”中。 The PHP code gives the images id's starting from "1" and so on. PHP代码给出了从“ 1”开始的图像id,依此类推。

Now with JavaScript i want it to automatically switch picture every 2,5 second. 现在使用JavaScript,我希望它每2.5秒自动切换一次图片。 It actually runs as i want it to in my Firebug Script, but nothing happens in the browser. 它实际上按照我的要求在Firebug脚本中运行,但是在浏览器中没有任何反应。 I already posted my JavaScript link in the bottom of the HTML body, and it doesn't help. 我已经将我的JavaScript链接发布在HTML主体的底部,但没有帮助。

Any help would be appreciated. 任何帮助,将不胜感激。

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

What happens is that always uses the same first element picture, hides it and then shows the second image, it does not actually iterate through all the pictures. 发生的情况是,始终使用相同的第一个元素图片,将其隐藏然后显示第二个图片,但实际上并没有遍历所有图片。

In your code, picture always is the first element, next is always the second. 在您的代码中,图片始终是第一个元素,第二个始终是第二个元素。

Also, it should not be a while loop since the callback is called once to change a picture, so change it to if, and reset to the first picture when it passes number of total elements. 另外,它也不应该是while循环,因为一次调用了回调才能更改图片,因此请将其更改为if,并在其通过总元素数时重置为第一张图片。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM