Javascript jQuery获取子div的最大宽度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5784388/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery get max width of child div's
提问by ONYX
I need to get the max width(just the one width) of the child div in the wrapper div element
我需要在包装器 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>
回答by Mark Kahn
Math.max.apply(Math, $('.image').map(function(){ return $(this).width(); }).get());
Per suggestion, I'll break that down:
根据建议,我将其分解:
$('.image').map(function(){
return $(this).width();
}).get();
The above gets a list of all .image
divs and converts it into a list of their widths. So you'll now have something like: [200, 300, 250, 100, 400]
. The .get()
, as Felix pointed out, is necessary to get an actual Array instead of a jQuery array.
以上获取所有.image
div的列表并将其转换为它们的宽度列表。所以,你现在会碰到这样的:[200, 300, 250, 100, 400]
。的.get()
,如菲利克斯指出的那样,有必要获得实际的阵列,而不是一个jQuery阵列。
Math.max
takes N arguments, so you have to call it as: Math.max(200, 300, 250, 100, 400)
, which is what the Math.max.apply
piece accomplishes.
Math.max
接受 N 个参数,因此您必须将其称为: Math.max(200, 300, 250, 100, 400)
,这就是该Math.max.apply
作品所要完成的。
回答by Jared Farrish
A not-so-difficult example function to consider; not as elegant as cwolves, but probably easier to follow if you're a beginner.
一个不太难考虑的示例函数;不像 cwolves 那样优雅,但如果您是初学者,可能更容易理解。
function getMaxChildWidth(sel) {
max = 0;
$(sel).children().each(function(){
c_width = parseInt($(this).width());
if (c_width > max) {
max = c_width;
}
});
return max;
}
回答by johndodo
I like this approach because it hits the sweet spot (IMHO) between core readability and shortness:
我喜欢这种方法,因为它在核心可读性和简短性之间达到了最佳点(恕我直言):
var max_w = 0;
$('#wrapper div.image').each(function() {
max_w = Math.max(max_w, parseInt($(this).width()));
})
YMMV of course.
当然是YMMV。