午夜更改图片顺序

Change the order of pictures at midnight

本文关键字:顺序 午夜      更新时间:2023-09-26

我有一组图片广告,我想在每天午夜更改顺序。

基本上,有一天它会像这个

<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来实现这一点。不关心我使用什么语言,只需要弄清楚。谢谢

试试这个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,从列表底部获取此数量的图像,并将它们移动到列表前面。

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

如果您可以访问数据库,那么在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;
  }
}

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

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

您可以使用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