Using jQuery 1.6.2
I have a variable number of floated divs inside a parent. The parent may have a fixed width but also may not.
I want to use jQuery to work out what number of divs are in one row, then inse开发者_JS百科rt a div with clear property set to both, so that the children may have variable heights and not make a mess of everything, and the parent may have a variable width.
It's a simple thing to do either in the markup or server side scripting if you know the width of the div and if you know how many children you want in a row - but what if everything is a bit more liquid?
Is there a simple way to do this, or am I going to have to do some working out of all the widths involved and a bit of clever maths to decide where to put the clear divs?
Try this:
Sample jQuery plugin (couldn't come up with a better plugin name):
(function ($) {
$.fn.extend({
addLineBreak: function (elementToInject) {
var minLeft = $(this).position().left;
return $(this).each(function () {
var position = $(this).position();
if (position.left > minLeft && $(this).prev().position().left >= position.left) {
$(elementToInject).insertBefore(this);
}
});
}
});
})(jQuery);
Usage:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>jQuery</title>
<script type="text/javascript" src="jquery-1.6.2.min.js"></script>
<script type="text/javascript" src="jquery.addLineBreak.js"></script>
<script type="text/javascript">
$(function () {
// '.inner' is the selector for the child elements!
$('.inner').addLineBreak('<div class="clear"></div>');
// on resize, remove the clear-elements, and inject new ones
$(window).resize(function () {
$('#tmp .clear').remove();
$('.inner').addLineBreak('<div class="clear"></div>');
});
});
</script>
<style type="text/css">
body {
background: black;
}
.inner {
float: left;
margin: 5px;
padding: 5px;
border: 1px solid #efefef;
}
.clear {
clear: both;
}
</style>
</head>
<body>
<div id="tmp">
<?php for ($i = 0; $i < 25; $i += 1): ?>
<div class="inner" style="width: <?php echo rand(100, 150); ?>px; height: <?php echo rand(100, 150); ?>px"><?php echo $i; ?></div>
<?php endfor; ?>
</div>
</body>
</html>
精彩评论