开发者

Tricky css/javascript floating task

I have a design that has several divs at varying widths/heights and I need them to float essentially to the top left. A simple css float:left will not work because it does not take advantage of the vertical space once it drops to a new line.

I assume I will need to use jQuery to dynamically position each div but I was hoping someone could lead me in the right direction.

This is what a standard float left would do: standard float http://www.media1designs.com/poc/superfloat/diagram_float_left.gif

This is what I need it to do: what I need http://www.media1designs.com/poc/开发者_运维知识库superfloat/diagram.gif

The sizes of the divs will change as the website's content updates so manually entering the positions is not an option.


Have you tried the masonry plugin?


You need to have an algorithm for determining where to place the next element given a set of existing elements and a bounding box (the container width & height). I'd start with plain english and just writing it down with pen and paper first - it's easier than code.

Once you have that, you'll use the jQuery width and height functions to get the sizes of the elements to position and I believe you'll want the css function for setting the top/left. The position of the elements should be "absolute" and the position of the containing element should be "relative". See all jQuery API methods.

Assuming you've written your layout algorithm as the function calculateOffset(element, container) returning an offset literal (e.g. {left: x, top: y}) and that you have a jQuery element list elements and a jQuery-wrapped container, you can do something like this to position everything:

elements.each(function() {
  $(this).css(calculateOffset($(this), container));
});

The hard part, of course, is writing calculateOffset. For that I recommend starting with something simple, like finding the highest possible (lowest top) place to put an element, favoring the left side (lowest left), then going from there.


I don't think I've ever heard of or seen a layout engine that would display things in that fashion. Most likely, you'll just have to write it yourself.

You'll need to create an API (at least in the way you think of things). Most likely, you'll end up with a Block (each div to be laid out) and a Container (the area holding the divs). Apply the appropriate methods, properties, and events to each of them, and you'll probably get there rather quickly.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜