用PHP一个接一个地加载图像


Loading images one after the other with PHP.

我有一段PHP代码,它从目录中加载图像,并一次将它们全部扔到页面上。我想知道如何添加一个一个接一个加载图像的功能,而不是一次加载所有图像。

$path = "images/page1/";
if (is_dir($path)){
    $handle = opendir($path);
}
else{
    echo 'No image directory';
}
$directoryfiles = array();
while (($file = readdir($handle)) !== false) {
    $newfile = str_replace(' ', '_', $file);
    rename($path . $file, $path . $newfile);
    $directoryfiles[] = $newfile;
}
echo '<table>';
foreach($directoryfiles as $directoryfile){
        if(strlen($directoryfile) > 3){
        echo '<tr><td> <img src="'.$path.$directoryfile.'"/>';
        echo '<br>'.$path.$directoryfile.'</td></tr>';
        }
    }
echo '</table>';
closedir($handle);

谢谢。

我认为,与其构建一个图像表,不如放第一个图像,并将其他图像的url存储在javascript变量中。然后,当你想加载其他图像(定时器,点击事件,…)时,你只需要更改原始图像的src参数。

您不能只使用PHP来实现这一点,因为PHP总是一次呈现页面并显示结果。如果你只是想要效果,你可以看看这个简单的jquery脚本:

如何创建淡入加载效果,一个接一个的图像

看起来Jquery是一种方法:

var dir = "images/page1/";
var fileextension = [".png", ".jpg"];
$.ajax({
//This will retrieve the contents of the folder if the folder is configured a 'browsable'
url: dir,
success: function (data) {
    //Lsit all png file names in the page
    $(data).find("a:contains(" + (fileextension[0]) + "), a:contains(" + (fileextension[1]) + ")").each(function () { 
        var filename = this.href.replace(window.location.host,"").replace("http:///",    "");
            jQuery(document).ready(function () {
            //hide a div after 3 seconds
                setTimeout( "$("body").append($("<img src=" + dir + filename + "></img>"));",3000 );
            });
        });
    }
});

警告:此代码尚未经过测试,但它应该让您了解如何处理问题。

如果使用输出函数,则可以使用PHP

这里有一个例子,数字将一个接一个地可见:

for ( $i = 1 ; $i <= 10 ; $i++ )
{
    echo $i."'n";
    flush();
    ob_flush();
    sleep(1);
}
  • flush()
  • ob_flush()

这可能对您有用:

echo '<table>';
$delay=250;
foreach($directoryfiles as $directoryfile){
        if(strlen($directoryfile) > 3){
            echo '<tr><td data-delay='.$delay.'> <img src="'.$path.$directoryfile.'"/>';
            echo '<br>'.$path.$directoryfile.'</td></tr>';
            $delay+=250;    
        }
    }
echo '</table>';