找到最长的元素(jQuery)

时间:2010-03-03 11:58:14

标签: jquery height addclass

我使用此脚本来均衡元素的高度:

(function ($) {
    $.fn.autoheight = function () {
        var height = 0,
            reset = $.browser.msie ? "1%" : "auto";
        return this.css("height", reset).each(function () {
            height = Math.max(height, this.offsetHeight);
        }).css("height", height).each(function () {
            var h = this.offsetHeight;
            if (h > height) {
                $(this).css("height", height - (h - height));
            };
        });
    };
})(jQuery);

我想为它添加一个额外的功能 - 添加类“最长”到均衡高度时找到的最长元素,我在上面的脚本中有什么变化?

非常感谢。

3 个答案:

答案 0 :(得分:2)

史蒂夫·克拉里奇上面提到的解决方案不起作用 - 对我来说很好; http://jsfiddle.net/ZqFp5/(仅在镀铬测试中)

虽然使用

 $("*")

选择器在大型DOM中效率不高,考虑在div中添加一个类以使用更具体的选择器。

 $(".foo") 

答案 1 :(得分:1)

考虑这个伪代码而不是任何东西,因为它没有经过测试(甚至没有运行)。更改了//新代码注释

中的代码
(function ($) {
    $.fn.autoheight = function () {
        var height = 0,
            highest = 0, //new code
            reset = $.browser.msie ? "1%" : "auto";
        return this.css("height", reset).each(function () {
            height = Math.max(height, this.offsetHeight);
            //new code
            if (height > highest) {
              highest = height;
              $("*").removeClass("longest");
              $(this).addClass("longest"); 
            };
            //new code
        }).css("height", height).each(function () {
            var h = this.offsetHeight;
            if (h > height) {
                $(this).css("height", height - (h - height));
            };
        });
    };
})(jQuery);

答案 2 :(得分:0)

我记得在这个网站上磕磕绊绊。这有帮助吗? http://www.queness.com/post/126/useful-and-handy-jquery-tips-and-tricks

读取数字10.相等高度的列。