修复我的随机图像定位脚本,使图像不重叠 [英] Fix my random image positioning script so the images don't overlap

查看:171
本文介绍了修复我的随机图像定位脚本,使图像不重叠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我制作了一个脚本(这是一个基于我的JS的小提琴)随机定位< li> 元素。

I made a script (here's a fiddle that builds upon my JS) for random positioning of <li> elements.

但元素相互重叠。

我如何修改我的代码以使项目不再重叠?

How can i modify my code so the items don't overlap anymore?

这是脚本:

var images = [];

function init() {
    $('.friend-selection li > div').each(function(){
        var id = this.id;
        var img = $('#img_' + id);
        var randomTop = 500*Math.random(); //random top position
        var randomLeft = 500*Math.random(); //random left position

        $("#parent_" + id).css({ //apply the position to parent divs
            top : randomTop,
            left : randomLeft
        });
    });
};

init(); 

我有这个HTML。带有li项目的ul:

I have this html. A ul with li items:

<li id="parent_picture1">
    <div id="picture1">    
        <div class="glow"></div>
        <img src="static/img/voorbeeld/vrouw.jpg" width="111" height="166" id="img_picture1">
        <span class="name">Naam Achternaam</span>
    </div>      
</li>


推荐答案

您需要保存每个随机位置的坐标一个数组。

You need to save the coordinates of each random position in an array.

每个< li>


  • 获取随机坐标对 random_coordinates

    • 检查 random_coordinates positions_array 中的每一对:

      • random_coordinates [0] +< li> 的宽度重叠 positions_array [i ] [0] +你< li> 范围的宽度在哪里?

        • 如果是,请重新开始。

        • Get a random coordinate pair random_coordinates.
          • Check random_coordinates against each pair in positions_array:
            • does random_coordinates[0] + the width of your <li> overlap the positions_array[i][0] + the width of your <li> range anywhere?
              • If yes, start over.

              • 如果是,请重新开始。

              这篇关于修复我的随机图像定位脚本,使图像不重叠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆