因此,我需要在网站中显示 2 或 3 个不同的图像,作为内容的简单视差分隔线。
我有一个由 4 张图像组成的数组,因此我能够随机化,而无需在同一页面中重复它们,尽管随机性不会那么明显。
我潜伏了一段时间,发现了这些
Random Image Display, Without Repeat, with Javascript
<script language="javascript">
var imagesArray = [
'images/img-1.jpg',
'images/img-2.jpg',
'images/img-3.jpg',
'images/img-4.jpg',
'images/img-5.jpg',
];
var usedImages = {};
var usedImagesCount = 0;
function displayImage() {
var num = Math.floor(Math.random() * (imagesArray.length));
if (!usedImages[num]) {
document.canvas.src = imagesArray[num];
usedImages[num] = true;
usedImagesCount++;
if (usedImagesCount === imagesArray.length) {
usedImagesCount = 0;
usedImages = {};
}
} else {
displayImage();
}
}
</script>
(这是为了在单击按钮时显示图像而创建的,如下所示
<input onclick="displayImage();" type=button value="Click Here">
我尝试根据我的需要调整它,但我页面上的调用没有产生任何结果)
(这个,我不太明白为什么,但我无法应用该解决方案。不确定是代码错误还是调用图像的方式错误......)
http://www.utopiamechanicus.com/article/not-so-random-image-rotation-in-php-for-html-the-sequel/
<?php
// rotate images randomly but w/o dups on same page - format:
// <img src='rotate.php?i=0'> - rotate image #0 - use 'i=1'
// for second, etc
// (c) 2004 David Pankhurst - use freely, but please leave in my credit
$images = array(// list of files to rotate - add as needed
"img1.gif",
"img2.gif",
"img3.gif",
"img4.gif",
"img5.gif");
$total = count($images);
$secondsFixed = 10; // seconds to keep list the same
$seedValue = (int) (time() / $secondsFixed);
srand($seedValue);
for ($i = 0; $i < $total; ++$i) { // shuffle list 'randomly'
$r = rand(0, $total - 1);
$temp = $images[$i];
$images[$i] = $images[$r];
$images[$r] = $temp;
}
$index = (int) ($_GET['i']); // image index passed in
$i = $index % $total; // make sure index always in bounds
$file = $images[$i];
header("Location: $file"); // and pass file reference back
?>
(这个应该可以通过以下方式调用:
<img src='mysite.com/rotate.php?i=0'>
但图像有时仍然重复)
它们对我不起作用,所以我决定开始一个新主题,因为我真的是 javascript 新手(实际上,我根本不知道写什么),并且不知道是什么最好的方法。我理解这就像随机化项目,为每个项目分配一个位置(数字、字符、[i] 等),然后在我的 php 页面中调用它。你们能帮帮我吗?
最佳答案
不确定您是否想要,但这会在页面上为您提供随机图像(不重复),每次都不同:
<?php
$img = array('img1.png', 'img2.png', 'img3.png', 'img4.png', 'img5.png', 'img6.png');
shuffle($img);
for($i=0; $i<3; $i++){
print '<img src="'.$img[$i].'"><br>';
}
?>
如果您希望每次调用接收一张图像,可能的解决方案之一是使用 session :
image.php:
<?php
session_start();
function getImage() {
$img = array('img1.png', 'img2.png', 'img3.png', 'img4.png', 'img5.png');
shuffle($img);
foreach($img as $key => $val) {
if (!is_array($_SESSION['img'])) {
return $val;
} elseif (count($_SESSION['img']) >= count($img)) {
$_SESSION['img'] = array();
}
if (is_array($_SESSION['img']) && !in_array($val, $_SESSION['img'])) {
return $val;
}
}
}
?>
page.php:
<?php
include 'image.php';
for ($i = 0; $i < 3; $i++) {
$currImg = getImage();
$_SESSION['img'][] = $currImg;
echo $currImg . '<br>';
}
?>
所有显示的图像都存储到 SESSION 变量中。当所有图像显示完毕后,该SESSION变量被重置,并开始新的循环。
关于javascript - 每页随机多张图片,不重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35749871/