本文介绍了点击随机图片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有关于如何刷新随机图像的代码,但我想它是像当我点击按钮随机图像显示我如何做呢?

I have code on how to random images on refresh however i wan it to be like when i click a button a random images shows up how do i do that?

这是随机图片的代码:

 <?
$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>';
?>


推荐答案

使用JavaScript:

Work with 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。

This works with /path/to/images/img-1.jpg.

您还可以创建一个数组:

You can also make an array:

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
}

查看注释/)和google一些代码,您将成功使用它。

Look at the comments (after //) and google some code and you will use this succesfully.

这篇关于点击随机图片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-25 23:29