开发者

How can I calculate the width of individual li with varying widths within a ul

开发者 https://www.devze.com 2023-03-19 12:44 出处:网络
Say I have this list below.Each image has a varying width and the a tag has a margin right of 15px which extends the list item a little more to give it some space from the next image.

Say I have this list below. Each image has a varying width and the a tag has a margin right of 15px which extends the list item a little more to give it some space from the next image.

<div id="otherproducts">
  <ul>
    <li><a href="products/sign-materials/"><img border="0" src="assets/images/subbrands/slider/slider.png" alt="" /></a></li>
    <li><a href="products/sign-materials/"><img border="0" src="assets/images/subbrands/slider/alight-slider.png" alt="" /></a></li&g开发者_开发技巧t;
    <li><a href="products/sign-materials/"><img border="0" src="assets/images/subbrands/slider/eclider.png" alt="" /></a></li>
    <li><a href="products/sign-materials/"><img border="0" src="assets/images/subbrands/slider/aluer.png" alt="" /></a></li>
    <li><a href="products/sign-materials/"><img border="0" src="assets/images/subbrands/slider/alucr.png" alt="" /></a></li>
  </ul>
</div>

How can I get jquery to give me the correct width of the items in my calculation below so I can give the UL the correct total width because currently the total is coming out much greater than it should...

var obj = $(this);              
var s = $("li", obj).length;
var w = $("li", obj).width(); 
var h = $("li", obj).height(); 
obj.width(w); 
obj.height(h); 
$("ul", obj).css('width',s*w);  


Your solution just measures the first item and then assumes each item is that long. Rather iterate over all items, measuring them individually, using jQuery's each:

Try

var width = 0;
$("li", obj).each(function(){width += $(this).width()});

$("ul", obj).width(width);


var ul= jQuery('ul'),
    finalWidth=0,finalHeight=0;

ul.find('li').each(function(){
    finalWidth+=jQuery(this).width();
    finalHeight+=jQuery(this).height();
});


ul.height(finalHeight).width(finalWidth);


Similar to Steffen Müller's approach, you probably want to use .each(), but you should use the .outerWidth(true) function to pick up the margin as well.

EDIT : Updated my code so it can replace yours.

var obj = $(this);
// calculate the max height of the <li>s
var max_h = 0;
$("li", obj).each(function() {
    max_h = Math.max( max, $(this).outerHeight(true) ); // include padding and margins
});
obj.height(max_h); // set the (presumedly <div>'s) height to the max_height
var w = 0;
$("li", obj).each(function() { 
    w += $(this).outerWidth(true);
});
$("ul", obj).width(w); // set the width of the <ul> to be the sum of the <li>'s widths
0

精彩评论

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