我有一个 HTML 页面,上面有 5 张图片(每张 48px × 48px)。我想在每次加载页面时在网页上的随机位置显示图像。
我不知道如何实现它,我只知道为此我需要 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>
最佳答案
这是一个相当简单的实现: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 + '%';
}
关于php - 每次加载页面时更改元素的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12445851/