在午夜更改图片的顺序

时间:2012-02-08 02:48:41

标签: php javascript jquery html

我有一组图片广告,我希望在午夜更改每天的订单。

基本上有一天会像这样

<img src="image1">
<img src="image2">
<img src="image3">
<img src="image4">

第二天看起来像这样

<img src="image4">
<img src="image1">
<img src="image2">
<img src="image3">

我怎样才能通过javascript,jquery或php实现这一目标。不关心我使用什么语言,只需要弄清楚。感谢..

4 个答案:

答案 0 :(得分:4)

试试这个http://jsfiddle.net/KQwf2/1/

HTML:

<img src="http://solarpanels2green.com/images/one.gif" title='1'>
<img src="http://solarpanels2green.com/images/two.gif" title='2'>
<img src="http://solarpanels2green.com/images/three.gif" title='3'>
<img src="http://solarpanels2green.com/images/four.gif" title='4'>

和js代码

var all = $('img'), 
        shift = Math.floor(
          (new Date().getTime() - new Date().getTimezoneOffset() * 60000)
         / (24 * 3600 * 1000)) % all.length;

all.filter(':gt(' + (all.length - shift - 1) + ')')
   .insertBefore(all.first());

它计算自1970年1月1日午夜以来经过的天数除以图像列表中的元素数量的MOD,从列表底部获取此数量的图像并将它们移到前面列表。

已更新以考虑访问者的时区。

答案 1 :(得分:2)

如果您有权访问数据库,那么在php中将每天的订单存储在数据库中将是一件简单的事情。然后,当页面加载时,您检查订单的日期,如果与当前日期不匹配则更新。更新过程包括通过php rand生成新订单。

如果您无权访问数据库,则需要提供仅基于日期的其他随机化机制。一种选择是生成日期的哈希并使用它来推动您的订购。

这里有一些非DB选项的php伪代码:

$fullhash = md5(date("Ymd"));
$hash = $fullhash;
$countImages = 4; //or whatever the actual number of images you have is
$shownImages = array();
while ($countShown < $countImages) 
{
  $num = ord($hash); //get ascii value of first char of $hash
  $num = $num % $countImages; //convert the number to something that corresponds to an image
  if (!(in_array($num, $shownImages)))
  {
    echo "<img src='image" . $num . "'>";
    $shownImages[] = $num;
  }
  $hash = substr($hash,1);
  if (strlen($hash) == 0)
  {
    $fullhash = md5($fullhash); //generate a new hash in case the previous one did not catch all images
    $hash = $fullhash;
  }
}

这看起来过于复杂。如果您可以在服务器上始终为随机数生成设置种子,那么您可以用它替换上面的大部分代码。然而,越来越多的实现正在逐渐远离种子自己的随机数生成器,这使得重复生成相同的随机数序列变得不那么容易。

答案 2 :(得分:1)

这是PHP中的一个仅取决于给定目录中一组图像的最后修改时间:

<?php

function cmp($a, $b){
  $atime = filemtime($a);
  $btime = filemtime($b);

  return $atime == $btime ? 0 : ($atime < $btime ? -1 : 1);
}

$paths = array();

if ($dh = opendir('images')){
  while (($path = readdir($dh)) !== false){
    if (substr($path, -4) == '.jpg'){
      array_push($paths, "images/$path");
    }
  }
}

$count = count($paths);
$offset = time() % $count;

usort($paths, 'cmp');

for ($i = 0; $i < $offset; $i++){
  $path = array_shift($paths);
  array_push($paths, $path);
}

?>

然后,在您的页面中需要它的任何地方:

<?php foreach ($paths as $path): ?>
  <img src="<?php echo $path; ?>" ... />
<?php endforeach; ?>

答案 3 :(得分:0)

你可以通过javascript获得时间。然后我会创建一个数组,随机化顺序并输出你的图像

var d = new Date();
var time= d.getHours();
if(time>=24){
  //code here for randomizing
}

http://www.w3schools.com/jsref/jsref_gethours.asp
http://www.javascriptkit.com/javatutors/randomorder.shtml