普通网友 2015-02-26 12:52
浏览 55
已采纳

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

报告相同问题?

悬赏问题

  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突