生成随机元素位置并防止JavaScript中的重叠 [英] Generate random element position and prevent overlapping in JavaScript
问题描述
我在页面上有一个持有者div,我想在随机位置加载小图像作为拼贴,每个都有10px填充。
I have a holder div on the page where I want to load small images in on random position as a collage with 10px padding on each.
如何确保图像永远不会相互重叠或持有div?
有没有我可以使用的插件或功能?
How can I make sure that images never overlap each other or holder div? Is there a plugin or function that I could use?
到目前为止我的代码:
<script src="jquery-1.3.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#my_canvas img").each(
function(intIndex) {
var l = Math.floor(Math.random() * $("#my_canvas").width());
var t = Math.floor(Math.random() * $("#my_canvas").height());
$(this).css("left", l);
$(this).css("top", t);
$(this).bind(
"click",
function() {
alert("l=" + l + " t=" + t);
}
);
}
);
});
<style type="text/css">
#my_canvas
{
background: #eee;
border: black 1px solid;
width: 800px;
height: 400px;
}
#my_canvas img
{
padding: 10px;
position:absolute;
}
</style>
<div id="my_canvas">
<img src="images/1.jpg" />
<img src="images/9.jpg" />
<img src="images/2.jpg" />
<img src="images/3.jpg" />
<img src="images/4.jpg" />
<img src="images/5.jpg" />
<img src="images/6.jpg" />
<img src="images/7.jpg" />
<img src="images/8.jpg" />
</div>
推荐答案
我猜没有插件。我将通过制作预定义的div网格并将随机图像加载到这些div来实现像Sander一样。它比计算图像尺寸/位置更容易,更快,并完成相同的工作。不是随机的,但在视觉上看起来不错:)
I guess there is no plugin. I will implement this like Sander suggested by making predefined div grid and just loading random images to those divs. It's easier and faster than calculating image dimenssions/positions and does pretty much the same job. Not random but visually looks good :)
这篇关于生成随机元素位置并防止JavaScript中的重叠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!