[英]Calculate largest width of a set of elements using jQuery
我做了一个快速的 Jsbin: http ://jsbin.com/ujabew/edit#javascript,html,live
我想要实现的是从链接中找出 3 个中最大的<section>
。 所以我想要的是,在循环运行之后,将var width
设置为任何宽度可能的最大可能数。
正在进行的代码发布在链接中
这里:
var maxWidth = Math.max.apply( null, $( elems ).map( function () {
return $( this ).outerWidth( true );
}).get() );
现场演示: http : //jsfiddle.net/rM4UG/
使用Math.max()
充实 Marc B 的评论:
$(document).ready(function(){
var maxWidth = 0;
$('.content ul li').each(function(){
var itemWidth = $(this).outerWidth(true);
maxWidth = Math.max(maxWidth, itemWidth)
});
});
我刚刚写了一个关于这个的函数。 我认为这可能会帮助其他人。 ( 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;
}
我相信您想查看下划线库。 具体来说,max方法
$(document).ready(function(){
var maxWidth = 0;
$('section').each(function(){
w = $(this).outerWidth(true);
if ( w > maxWidth)
maxWidth = w;
});
});
将.each()
循环更改为:
var thisWidth = $(this).outerWidth(true);
if (thisWidth > width) {
width = thisWidth;
}
这是我的想法:
$(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);
}
});
});
我添加了元素数量的计数,然后运行Math.max
以在每个循环完成时获得最大数量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.