【问题标题】:Random images on click点击随机图片
【发布时间】:2012-02-13 08:52:31
【问题描述】:

我有关于如何在刷新时随机显示图像的代码,但是我希望当我单击按钮时会显示随机图像,我该怎么做?

这是随机图像的代码:

 <?
$imglist='';
//$img_folder is the variable that holds the path to the banner images. Mine is images/tutorials/
// see that you don't forget about the "/" at the end 
$img_folder = "images/tutorials/";

mt_srand((double)microtime()*1000);

//use the directory class
$imgs = dir($img_folder);

//read all files from the directory, checks if are images and ads them to a list (see below how to display flash banners)
while ($file = $imgs->read()) {
if (eregi("gif", $file) || eregi("jpg", $file) || eregi("png", $file))
$imglist .= "$file ";

} closedir($imgs->handle);

//put all images into an array
$imglist = explode(" ", $imglist);
$no = sizeof($imglist)-2;

//generate a random number between 0 and the number of images
$random = mt_rand(0, $no);
$image = $imglist[$random];

//display image
echo '<img src="'.$img_folder.$image.'" border=0>';
?>

【问题讨论】:

    标签: php image random click


    【解决方案1】:

    使用 JavaScript:

    document.getElementById('the-img-id').onclick = function() {
      var randomInt = Math.round(Math.random() * 12); // 12 is the max
      this.src = '/path/to/images/img-'+randomInt+'.jpg'; // replace the src
    }
    

    这适用于 /path/to/images/img-1.jpg。

    你也可以做一个数组:

    var myImages = [
      'foo.jpg',
      'bar.jpg',
      'something.jpg',
      'someotherting.jpg',
      'ahhhanpng.png'
    ];
    
    // select a element with id="the-img-id"
    document.getElementById('the-img-id').onclick = function() {
      var randomInt = Math.round(Math.random() * myImages.length-1 ); // Create random number
      this.src = '/path/to/images/'+myImages[randomInt]; // replace the src with the new img
    }
    

    查看 cmets(在 // 之后)并 google 一些代码,您将成功使用它。

    【讨论】:

    • 到 img-1.jpg 和 img-2.jpg 或者你可以用文件在 JS 中创建一个数组
    【解决方案2】:

    您将需要使用 javascript。使用 getElementById("idOfImageElement").src = "newSrc"。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多