jQuery 获取子 div 的最大宽度

新手上路,请多包涵

我需要在包装器 div 元素中获取子 div 的最大宽度(只是一个宽度)

 <div id="wrapper">
    <div class="image"><img src="images/1.jpg"></div>
    <div class="image"><img src="images/2.jpg"></div>
    <div class="image"><img src="images/3.jpg"></div>
    <div class="image"><img src="images/4.jpg"></div>
    <div class="image"><img src="images/5.jpg"></div>
    <div class="image"><img src="images/6.jpg"></div>
</div>

原文由 ONYX 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 564
2 个回答
Math.max.apply(Math, $('.image').map(function(){ return $(this).width(); }).get());

根据建议,我将其分解:

 $('.image').map(function(){
   return $(this).width();
}).get();

上面获取了所有 .image div 的列表,并将其转换为宽度列表。所以你现在会有类似的东西: [200, 300, 250, 100, 400] 。正如 Felix 指出的那样, .get() 是获取实际数组而不是 jQuery 数组所必需的。

Math.max 接受 N 个参数,所以你必须将其称为: Math.max(200, 300, 250, 100, 400) ,这是 Math.max.apply 部分完成的。

原文由 user578895 发布,翻译遵循 CC BY-SA 4.0 许可协议

一个不难考虑的示例函数;不像 cwolves 那样优雅,但如果您是初学者,可能更容易理解。

 function getMaxChildWidth(sel) {
    max = 0;
    $(sel).children().each(function(){
        c_width = parseInt($(this).width());
        if (c_width > max) {
            max = c_width;
        }
    });
    return max;
}

http://jsfiddle.net/userdude/rMSuJ/1/

原文由 Jared Farrish 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏