jQuery获得子div的最大宽度

ONY*_*NYX 25 javascript jquery

我需要在包装器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>
Run Code Online (Sandbox Code Playgroud)

Mar*_*ahn 71

Math.max.apply(Math, $('.image').map(function(){ return $(this).width(); }).get());
Run Code Online (Sandbox Code Playgroud)

根据建议,我会打破这个:

$('.image').map(function(){
   return $(this).width();
}).get();
Run Code Online (Sandbox Code Playgroud)

以上获取所有.imagediv 的列表并将其转换为宽度列表.所以你现在会有类似的东西:[200, 300, 250, 100, 400].的.get(),如菲利克斯指出的那样,有必要获得实际的阵列,而不是一个jQuery阵列.

Math.max需要N个参数,所以你必须把它称为:Math.max(200, 300, 250, 100, 400),这就是Math.max.apply作品的成就.


Jar*_*ish 8

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

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

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

  • 你在js小提琴上用beecker破解我.我是jQuery的新手,所以我一点一点地学习.谢谢 (2认同)

joh*_*odo 7

我喜欢这种方法,因为它在核心可读性和简短性之间达到了最佳点(恕我直言):

var max_w = 0;
$('#wrapper div.image').each(function() {
    max_w = Math.max(max_w, parseInt($(this).width()));
})
Run Code Online (Sandbox Code Playgroud)

当然是YMMV。