Javascript 如何计算ul内具有不同宽度的单个li的宽度

Javascript 如何计算ul内具有不同宽度的单个li的宽度,javascript,jquery,Javascript,Jquery,假设我有下面的列表。每个图像都有不同的宽度,a标记的右边距为15px,这会稍微扩展列表项,以便与下一个图像保持一定的距离 <div id="otherproducts"> <ul> <li><a href="products/sign-materials/"><img border="0" src="assets/images/subbrands/slider/slider.png" alt="" /></a>&

假设我有下面的列表。每个图像都有不同的宽度,a标记的右边距为15px,这会稍微扩展列表项,以便与下一个图像保持一定的距离

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

您的解决方案只是测量第一个项目,然后假设每个项目都那么长。而是使用jQuery的每个:

试一试


与Steffen Müller的方法类似,您可能希望使用
.each()
,但您也应该使用该函数来提取边距

编辑:更新了我的代码,以便可以替换你的代码

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
var obj=$(此项);
//计算
  • s的最大高度 var max_h=0; $(“li”,obj)。每个(函数(){ max_h=Math.max(max,$(this.outerHeight(true));//包括填充和边距 }); 物体高度(最大高度);//将(假定的)高度设置为最大高度 var w=0; $(“li”,obj).each(function(){ w+=$(此).outerWidth(真); }); $(“ul”,obj)。宽度(w);//将
      的宽度设置为
    • 宽度的总和
  • 您能告诉我如何将其包含在我的上述代码中吗?我已经编辑了我的答案以匹配。让我知道你对新代码的了解。
    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);
    
    var width = 0;
    $("li", obj).each(function(){width += $(this).width()});
    
    $("ul", obj).width(width);
    
    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