【问题标题】:Find the longest element (jQuery)查找最长的元素(jQuery)
【发布时间】:2011-01-23 04:15:41
【问题描述】:

我使用这个脚本来平衡元素的高度:

(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);

我只想为其添加一项额外功能 - 将class 'longest' 添加到均衡高度时发现的最长元素,我要在上述脚本中进行哪些更改?

非常感谢。

【问题讨论】:

  • 它是关于均衡高度,所以“最长”更合适?
  • “最高”或“最高”或可能“最大”更合适。宽度 -> 最宽,高度 -> 最高/最高,长度 -> 最长。

标签: jquery height addclass


【解决方案1】:

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

虽然使用了

 $("*")

选择器在大型 DOM 中效率较低,如果可能,请考虑向 div 中添加一个类以使用更具体的选择器。

 $(".foo") 

【讨论】:

    【解决方案2】:

    认为这个比任何东西都更伪代码,因为它没有经过测试(甚至没有运行)。 //新代码注释内的更改代码

    (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);
    

    【讨论】:

    • 刚刚检查了 Alex 的 jsFiddle 示例,它似乎工作正常。您可以使用 Firebug 检查结果 DOM,并查看其中一个 div 添加了“最长”类。
    【解决方案3】:

    我记得偶然发现了这个网站。这有帮助吗? http://www.queness.com/post/126/useful-and-handy-jquery-tips-and-tricks

    读取数字 10。等高的列。

    【讨论】:

    • 不,我用的是完美的,我只需要将class添加到最高的元素。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-24
    • 1970-01-01
    • 1970-01-01
    • 2010-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多