Home >Web Front-end >JS Tutorial >The principle and implementation of jquery secondary navigation content equalization_jquery

The principle and implementation of jquery secondary navigation content equalization_jquery

WBOY
WBOYOriginal
2016-05-16 17:25:371228browse

This is an algorithm from a project I did last year. I personally think it’s pretty good, so I’ll share it with you.

Background: Some content in the header navigation and secondary navigation is too long and too ugly to read in one column, so it needs to be divided into two columns. It should be divided as equally as possible by block. There is no limit to the order of arrangement.

Principle:

1. Treat each secondary navigation as an independent one and divide it into multiple blocks. Calculate the height of each block and arrange them in ascending order.

2. Find the total height of each block and divide by 2 to get the average highest height.

3. Starting from the block with the highest height, if the height is greater than the average height, then this block is placed on side A, and the others are assigned to side B.

4. If it is less than this height, the average height becomes the value minus the highest height.

5. Take the ratio of the remaining highest height to the average height. If the height is greater than the average height, put this piece into side A and the others to side B.

6. Loop 3-5 until all blocks are over.

This is the main idea of ​​this code, which divides the content of a navigation into two equal columns.

Implementation:

When there is only one block, no comparison is needed

Copy code The code is as follows:

if (arrs.length <= 1) {
$(obj).css({
width : "150px"
} );
return;
}

When the total height is not higher than the height limit, there is no need to divide into two columns:
Copy code The code is as follows:

if (sum < limitHeight) {
$(obj).css({
width : "150px "
});
return;
}

Principle implementation code:
Copy code The code is as follows:

for (var i = arrs.length - 1; i > -1; i--) {
var _h = $(arrs[i]).height();
if (_h < gap) {
gap = gap - _h;
oldArrs.push(arrs[i]);
} else {
newArrs.push(arrs[i]);
}
}

oldArrs, ​​newArrs represents A, B
demo download
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn