普通网友 2015-02-26 04:52
浏览 56
已采纳

使用PHP和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);
};  

展开全部

  • 写回答

1条回答 默认 最新

  • duanchuan6350 2015-02-26 05:19
    关注

    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);
    };
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部