首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何正确地使用jQuery来修复这个fencepost情况?

如何正确地使用jQuery来修复这个fencepost情况?
EN

Stack Overflow用户
提问于 2015-09-02 21:09:44
回答 3查看 46关注 0票数 1

我有个功能

代码语言:javascript
复制
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);
}

这是非常不言而喻的。

示例用例:

代码语言:javascript
复制
giveTheseEqualHeight('.service-column h3'); 

将所有属于类h3元素的service-column子类的元素都提高到比高度最高的元素更小的高度,从而使它们具有相同的高度。

问题是循环

代码语言:javascript
复制
             these.each(function(){
                var thisHeight = $(this).height();
                if (thisHeight > maxHeight) maxHeight = thisHeight;                
             });

不需要在第一次迭代时执行它的主体--这相当于无用的操作。而不是these.each,我想从第二项开始。这个是可能的吗?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2015-09-02 21:18:07

如果得到高度数组,然后使用本机Math.max取最大值,则可以避免计算第一个元素的高度:

代码语言:javascript
复制
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);
}

下面是它的一个演示:

代码语言:javascript
复制
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')
代码语言:javascript
复制
div {display: inline-block;background: #EEE; vertical-align: top;}
代码语言:javascript
复制
<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>

票数 1
EN

Stack Overflow用户

发布于 2015-09-02 21:13:22

jQuery有slice。从第二个元素中切片(索引1)。如果省略了结尾,它会一直分割到结尾。

代码语言:javascript
复制
these.slice(1).each(...);
票数 1
EN

Stack Overflow用户

发布于 2015-09-02 21:17:45

使用greater-than选择器选择索引大于所提供的数字的所有元素。

  • http://api.jquery.com/gt-selector/
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32363157

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档