javascript 使用jQuery计算一组元素的最大宽度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8853606/
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
Calculate largest width of a set of elements using jQuery
提问by benhowdle89
I have made a quick Jsbin: http://jsbin.com/ujabew/edit#javascript,html,live
我做了一个快速的 Jsbin:http://jsbin.com/ujabew/edit#javascript,html,live
What i'm trying to achieve is to find out which is the largest <section>
out of the 3 from the link. So what i'd like is to, after the loop runs, is to have var width
set to the largest possible number that any of the widths could be.
我想要实现的是<section>
从链接中找出 3 个中最大的那个。所以我想要的是,在循环运行后,var width
将任何宽度设置为最大的可能数字。
Code in progress posted in link
正在进行的代码发布在链接中
回答by ?ime Vidas
Here:
这里:
var maxWidth = Math.max.apply( null, $( elems ).map( function () {
return $( this ).outerWidth( true );
}).get() );
Live demo:http://jsfiddle.net/rM4UG/
现场演示:http : //jsfiddle.net/rM4UG/
回答by Carl Raymond
Fleshing out Marc B's comment, using Math.max()
:
充实 Marc B 的评论,使用Math.max()
:
$(document).ready(function(){
var maxWidth = 0;
$('.content ul li').each(function(){
var itemWidth = $(this).outerWidth(true);
maxWidth = Math.max(maxWidth, itemWidth)
});
});
回答by powerbuoy
Change the .each()
loop to this:
将.each()
循环更改为:
var thisWidth = $(this).outerWidth(true);
if (thisWidth > width) {
width = thisWidth;
}
回答by Einar ólafsson
This was my idea
这是我的主意
$(document).ready(function(){
var elements = $('.content ul li'); var count = elements.length -1; var width = []; elements.each(function(n){ width.push($(this).outerWidth(true)); if (count == n) { width = Math.max.apply(Math, width); } });
});
$(document).ready(function(){
var elements = $('.content ul li'); var count = elements.length -1; var width = []; elements.each(function(n){ width.push($(this).outerWidth(true)); if (count == n) { width = Math.max.apply(Math, width); } });
});
I added the count of amount of elements and than runs the Math.max to get the largest number when the each loop is done.
我添加了元素数量,然后运行 Math.max 以在每个循环完成时获得最大数量。
回答by Mr_Green
I have just written a function regarding this. I thought it might help others. (jQuery)
我刚刚写了一个关于这个的函数。我认为这可能会帮助其他人。( jQuery)
$.fn.largerWidth = function () { //function(p)
// where 'p' can be clientWidth or offsetWidth
// or anything else related to width or height
var s = this,m;
for (var i = 0; i < s.length; i++) {
var w = s[i].offsetWidth; // s[i][p];
(!m || w > m) ? (m = w) : null
}
return m;
}
回答by Zee Spencer
I believe you want to look into the underscorelibrary. Specifically, the max method
我相信您想查看下划线库。具体来说,max方法
回答by kaz
$(document).ready(function(){
var maxWidth = 0;
$('section').each(function(){
w = $(this).outerWidth(true);
if ( w > maxWidth)
maxWidth = w;
});
});