jQuery – 页面上最宽的项目

如何使用jQuery在网页上找到最宽的项目(宽度设置为css或作为属性)?

不会快,但应该做的伎俩

var widest = null; $("*").each(function() { if (widest == null) widest = $(this); else if ($(this).width() > widest.width()) widest = $(this); }); 

这应该可以解决问题

这个版本可能会稍微快一点(但绝对不是那么clienat):

 var widest = null; // remember the width of the "widest" element - probably faster than calling .width() var widestWidth = 0; $("*").each(function() { if (widest == null) { widest = $(this); widestWidth = $(this).width(); } else if ($(this).width() > widestWidth) { widest = $(this); widestWidth = $(this).width(); } }); 

我还建议你限制你经历的节点类型(即使用div而不是*)

很棒的回答Niko!

我稍微构建它,以便它只显示页面上可见的元素,因为有时它会返回宽度设置较大但可能有display:none set的例子;

 var widest = null; $("*").each(function() { if (widest === null && $(this).is(':visible') ) { widest = $(this); } else if ( $(this).is(':visible') && $(this).width() > widest.width() ) { widest = $(this); } });