每次加载页面时更改元素位置

4

我有一个 HTML 页面,其中有 5 张图片(每张图片大小均为 48 像素 × 48 像素)。我希望每次加载页面时,这些图像出现在页面的随机位置。

我不知道如何实现这一点,但我知道我需要使用 CSS 和 JavaScript(用于随机化)。有任何想法或建议吗?

以下是示例 HTML 代码:

  <a href="http://twitter.com/"><img alt="Twitter" src="/images/twitter-48.png" /></a>
  <a href="http://facebook.com/><img alt="Facebook" src="/images/facebook-48.png" /></a>
  <a href="https://plus.google.com/"><img alt="Google Plus" src="/images/plus-48.png" /></a>
  <a href="https://github.com/"><img alt="GitHub" src="/images/github-48.png" /></a>

1
关于 PHP:不要忘记,如果可能并且安全的话,最好在客户端执行工作以卸载服务器。关于随机定位 - 你已经有容器或图像元素了,只需要随机分配 src,还是想设置 position:fixed; 并在 body 中随机放置图像? - Eugene Naydenov
@Santosh,请提供更多细节。你所说的“随机位置”是什么意思?它应该是一些容器包装器,其中图像将被绝对定位,还是其他什么东西?请提供一些标记。 - Dmitry Koroliov
@caligula,他的请求对我来说似乎非常简单明了,他想要在页面上随机排列元素。他不确定应该使用哪种技术,是标记/ CSS / JavaScript。 - Korvin Szanto
@caligula,我已经更新了问题,还没有做任何CSS方面的工作。 - Santosh Kumar
@EvgeniyNaydenov,请看我的更新问题,我没有改动CSS部分。如果我想在JavaScript中完成这个怎么办? - Santosh Kumar
5个回答

1
这是一个相当简单的实现:http://jsfiddle.net/Eu8wT/
$('div.randomizeme').css({
    top: Math.random() * 100+'%',
    left: Math.random() * 100+'%'
});​

在多个元素上应用此操作:

$('div.randomizeme').each(function(){
    $(this).css({
        top: Math.random() * 100+'%',
        left: Math.random() * 100+'%'
    });
});​

这是没有使用jQuery的同样内容:

var elements = document.querySelectorAll('.randomizeme');
for (var i in elements) {
    elements[i].style.top = Math.random() * 100 + '%';
    elements[i].style.left = Math.random() * 100 + '%';
}​

嘿,它在jsFiddle上运行正常,但对我来说不起作用。你能否查看一下 - Santosh Kumar
你正在加载脚本之前加载图像,如果你反过来做就没问题了,或者你可以使用 window.onLoad = function(){ } 等待整个页面加载。 - Korvin Szanto
将脚本移动到闭合的body标签上方(更新了该链接),但仍然存在问题。 - Santosh Kumar
它在jsFiddle之外无法工作,你能提供一个真实世界的(在网页上)例子吗? - Santosh Kumar
@Santosh 这是“无jQuery”版本:http://fiddle.jshell.net/dSAzp/show/。请记住,您只能有一个`window.onload`定义,因此,如果您的页面具有jQuery或另一个使用`window.onload`的库,请尝试使用`document.onload`。我还应该让您知道,我之前说过`window.onLoad`,这是不正确的,应该是`window.onload`。 - Korvin Szanto
这是一个永远不会超出页面边界的示例:http://jsfiddle.net/Jfduu/ - Korvin Szanto

1
一种使用纯JavaScript(无库)的解决方案。
var imgs = document.querySelectorAll('.rand'), 
    len = imgs.length, 
    /* subtract the width/ height of images */
    w = document.body.clientWidth - 48, 
    h = document.body.clientHeight - 48;

for(var i = 0; i < len; i++) {
  imgs[i].style.top = Math.floor(Math.random() * h) + 'px';
  imgs[i].style.left = Math.floor(Math.random() * w) + 'px';
}

工作演示


@Ana,我在CodePen上测试通过,但我不知道为什么它在我的电脑上无法运行。你能帮我检查一下吗 - Santosh Kumar
我不知道为什么,但我已经更新了笔和我的答案。这也更简单,我认为它应该可以工作 :-? - Ana
@Ana 真的吗?我已经更新了JavaScript,但是它仍然像以前一样。图像似乎重叠在一起,因此只显示一个图像。你有在你的浏览器(本地)中尝试过吗? - Santosh Kumar
我在你的网站控制台上运行了它。我现在想我已经弄清楚为什么它不起作用了。它说document.bodynull,这很合理,因为你把它放在body之前的head中。你应该把脚本放在关闭body标签之前。 - Ana
因为您说您的图像是每个48px x 48px,但我使用的不是这样大小的,实际上它们更大,因此我需要将它们缩小。 - Ana
显示剩余2条评论

-1
假设您已经将图像硬编码到HTML文档中。如果您想使用PHP完成此操作,您需要为每个元素添加一个style属性。在您的情况下,您的图像包含在<a>标记中,因此您需要随机定位<a>标记而不是图像...
function generateRandomPositions(){

  // define maximum and minimum 'top' values
  $maxTop = 1000;
  $minTop = 0;

  // define maximum and minimum 'left' values    
  $maxLeft = 1000;
  $minLeft = 0; 


  $styleProperties = array(
    'position:absolute',
    'top:'.rand($minTop,$maxTop) . 'px',
    'left:'.rand($minLeft,$maxLeft) . 'px'
  );

  return ' style="'.implode(';',$styleProperties).'" ';
}

该函数将返回类似于以下字符串的结果 -
style="position:absolute;top:10px; left:45px;"

现在你需要做的就是为页面上的每个图像调用这个函数 -
<a <?php echo generateRandomPositions();?> ><img src="...
<a <?php echo generateRandomPositions();?> ><img src="...
<a <?php echo generateRandomPositions();?> ><img src="...
<a <?php echo generateRandomPositions();?> ><img src="...

您的<a>标签现在将包含随机CSS定位参数,它们的图像也会随之移动。

正如您所看到的,使用PHP生成内联CSS属性的方法有点反向。JavaScript可能是获得您想要的最好方法,还有其他答案可以涵盖它。您可以使用CSS最初隐藏元素,然后在设置随机定位后使用JavaScript显示它们。


参考资料 -


1000x1000 屏幕?使用百分比会更有意义,而且这种操作不应该使用 PHP 进行。 - Korvin Szanto
@kor - 100opx 的限制只是我给出的一个例子。我清楚地知道 PHP 不是做这个的方式,但原帖确实在询问 PHP - 这是一种替代方案。 - Lix
1
不想冒犯,但他的问题是哪种技术最好使用,然后他说他认为php是最好的。我很高兴你理解了这一点,但你应该指出有更好的方法。 - Korvin Szanto
@Lix 如我所料,有没有什么方法可以防止重叠? - Santosh Kumar
@san - 这就是随机化的问题所在。您必须重新生成一个随机位置,并每次将其与已经生成的现有值进行比较。请记得将元素的宽度和高度添加到这些值中,以确保没有重叠。 - Lix
@Lix 我已将 $maxTop$maxLeft 更改为 100 并将 px 替换为 %。但我不希望图像出现在折叠线以下。我尝试将 maxTop 和 maxLeft 更改为 95%,但它没有起作用。 - Santosh Kumar

-1
<?php
$images= array(
    'twitter-48.png',
    'facebook-48.png',
    'plus-48.png',
    'github-48.png'
);
$keys= range(0, count($images)- 1);
shuffle($keys);
foreach($keys as $key) {
    print "<div>{$images[$key]}</div>";
}

编辑:

<?php
$images= array(
    array('href'=> 'http://twitter.com/', 'alt'=> 'Twitter', 'src'=> '/images/twitter-48.png'),
    array('href'=> 'http://facebook.com/', 'alt'=> 'Facebook', 'src'=> '/images/facebook-48.png'),
    array('href'=> 'https://plus.google.com/', 'alt'=> 'Google Plus', 'src'=> '/images/plus-48.png'),
    array('href'=> 'https://github.com/', 'alt'=> 'GitHub', 'src'=> '/images/github-48.png')
);
$keys= range(0, count($images)- 1);
shuffle($keys);
?>
<div class='location1'>
    <a href='<?php print $images[$keys[0]]['href']; ?>'><img alt='<?php print $images[$keys[0]]['alt']; ?>' src='<?php print $images[$keys[0]]['src']; ?>'></img></a>
</div>
<div class='location2'>
    <a href='<?php print $images[$keys[1]]['href']; ?>'><img alt='<?php print $images[$keys[1]]['alt']; ?>' src='<?php print $images[$keys[1]]['src']; ?>'></img></a>
</div>
<div class='location3'>
    <a href='<?php print $images[$keys[2]]['href']; ?>'><img alt='<?php print $images[$keys[2]]['alt']; ?>' src='<?php print $images[$keys[2]]['src']; ?>'></img></a>
</div>
<div class='location4'>
    <a href='<?php print $images[$keys[3]]['href']; ?>'><img alt='<?php print $images[$keys[3]]['alt']; ?>' src='<?php print $images[$keys[3]]['src']; ?>'></img></a>
</div>

你的代码中有两个错误,1. 你没有关闭 PHP 标签。2. 你只是使用了文本而不是图片,在代码中应该使用 img src。另外,我希望图片能够散布在整个页面上,而不仅仅是在一列中。 - Santosh Kumar
稍微好一点,我会重申@HanhNghien所说的话; 结束标签是可选的。 - Korvin Szanto
@HanhNghien 但仍然在单列中。 - Santosh Kumar
<div class='location1'>...</div> 放在 Header 中,将 <div class='location2'>...</div> 放在左侧,将 <div class='location1'>...</div> 放在右侧,将 <div class='location1'>...</div> 放在 Footer 中或任何位置 - HanhNghien
@HanhNghien 这个问题是关于随机化的,可以在任何地方进行。无论如何,还有其他答案可以实现这一点。 - Santosh Kumar

-2

试试这个:

$images = array('1.gif', '2.gif', '3.gif');
$images = array_shaffle($images);
foreach ($images as $image) {
  echo "<img src='{$image}' />;
}

1
array_shuffle?另外,你没有关闭你的“”。最后,这并没有完全回答所提出的问题。 - Korvin Szanto
1
更好的写法是 bool shuffle(array &$array); 我刚刚编辑了这个答案,等待接受。 - Eugene Naydenov
@evg - 请不要编辑其他人帖子中的代码块。这可能会极大地改变提供的解决方案的结果。在这种情况下,最好为原始帖子留下评论,让他们自己处理。 - Lix

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接