Positioning multiple, random sized, absolutely positioned elements so they don't overlap

ⅰ亾dé卋堺 提交于 2019-12-17 16:39:23

问题


Ok I need to be able to position a bunch of random sized absolutely positioned words on a page but I don't want any of the elements to overlap.

The end goal is to have a fluid word cloud that responds to user interaction (remember the Google Balls Doodle?). I would really like to build this from scratch to develop my understanding of this type of development. Any help in this department would also be appreciated :)


回答1:


I'm not sure if you also want to position the words randomly inside a container, but i've written a fiddle that does just that. You can modify the code to position one word right after the other if you want to though. I think the key part is the method to check if there's a collision.

see http://jsfiddle.net/fZtdt/13/

EDIT: Be aware that this is very simple and unoptimized code. If for example you would add to many words, chances are that the script won't be able to fit all words inside the container, and get into an endless loop.




回答2:


I have forked Jules' script to add this improvement : the search for a non-overlapping region is bounded (otherwise the original script will loop I believe), and the best region (the one with the smallest overlap) is selected.

see http://jsfiddle.net/Vnyvc/21/

play with the maxSearchIterations variable and/or the size of the whole region, it really makes a difference.



来源:https://stackoverflow.com/questions/6224571/positioning-multiple-random-sized-absolutely-positioned-elements-so-they-dont

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!