我有个功能
function giveTheseEqualHeight ( selector )
{
// selector: CSS selector of elements on the page to be forced to have the same height
var these = $(selector);
if (these.length < 2) return;
these.height('auto');
var maxHeight = these.first().height();
these.each(function(){
var thisHeight = $(this).height();
if (thisHeight > maxHeight) maxHeight = thisHeight;
});
these.height(maxHeight);
}这是非常不言而喻的。
示例用例:
giveTheseEqualHeight('.service-column h3'); 将所有属于类h3元素的service-column子类的元素都提高到比高度最高的元素更小的高度,从而使它们具有相同的高度。
问题是循环
these.each(function(){
var thisHeight = $(this).height();
if (thisHeight > maxHeight) maxHeight = thisHeight;
});不需要在第一次迭代时执行它的主体--这相当于无用的操作。而不是these.each,我想从第二项开始。这个是可能的吗?
发布于 2015-09-02 21:18:07
如果得到高度数组,然后使用本机Math.max取最大值,则可以避免计算第一个元素的高度:
function giveTheseEqualHeight(selector) {
var these = $(selector);
if (these.length < 2) return;
these.height('auto');
var maxHeight = Math.max.apply(null, these.map(function(el) {
return $(this).height();
}));
these.height(maxHeight);
}下面是它的一个演示:
function giveTheseEqualHeight(selector) {
var these = $(selector);
if (these.length < 2) return;
these.height('auto');
var maxHeight = Math.max.apply(null, these.map(function(el) {
return $(this).height();
}));
these.height(maxHeight);
}
giveTheseEqualHeight('div')div {display: inline-block;background: #EEE; vertical-align: top;}<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Lorem</div>
<div>Test <br>rest</div>
<div>Test <br> and rest <br>on the <br>west</div>
发布于 2015-09-02 21:13:22
jQuery有slice。从第二个元素中切片(索引1)。如果省略了结尾,它会一直分割到结尾。
these.slice(1).each(...);发布于 2015-09-02 21:17:45
使用greater-than选择器选择索引大于所提供的数字的所有元素。
https://stackoverflow.com/questions/32363157
复制相似问题