简体   繁体   中英

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. The PHP code gives the images id's starting from "1" and so on.

Now with JavaScript i want it to automatically switch picture every 2,5 second. It actually runs as i want it to in my Firebug Script, but nothing happens in the browser. I already posted my JavaScript link in the bottom of the HTML body, and it doesn't help.

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:

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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