最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Positioning multiple, random sized, absolutely positioned elements so they don't overlap - Stack Overflow

programmeradmin3浏览0评论

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 :)

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 :)

Share Improve this question asked Jun 3, 2011 at 8:10 wilsonpagewilsonpage 17.6k23 gold badges105 silver badges149 bronze badges 2
  • May be useful to set the font size, and get the surrounding element's height / width first, then go about positioning to begin with. jsfiddle.net/yYB7t – minikomi Commented Jun 3, 2011 at 8:20
  • @minikomi any idea how to do the positioning? I am aware how to get an element's hight and width. – wilsonpage Commented Jun 3, 2011 at 9:40
Add a comment  | 

2 Answers 2

Reset to default 13

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.

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.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论