【问题标题】:Jquery - Calculating height sum of elementsJquery - 计算元素的高度总和
【发布时间】:2016-09-28 05:40:04
【问题描述】:

要计算元素的高度总和并在我正在使用的 .body div 上应用为“最小高度”:

$(window).on("resize", function () {
  var a = $("body").outerHeight();
  var b = $(".header").outerHeight(true);
  var c = $(".footer").outerHeight(true);
  var d = $(".bottom").outerHeight(true);
  $(".body").css("min-height", a - b - c - d);
}).trigger("resize");

如果所有元素都存在于 html 上,它可以正常工作,但如果缺少一个元素,它就会损坏。

好 - https://jsfiddle.net/0ggr3ptv/1/

不好 - https://jsfiddle.net/oed11Lzm/1/ .bottom div 丢失。

如何排除缺失的元素或者让他们为0?

使用 jQuery 3.1.1 和 .bottom div 变得未定义。我该如何解决?谢谢

【问题讨论】:

    标签: jquery html css


    【解决方案1】:

    使用

    var d = $(".bottom").outerHeight(true) || 0;
    

    代替

    var d = $(".bottom").outerHeight(true);
    

    将默认值设置为0。有更多信息可以找到here

    【讨论】:

      【解决方案2】:

      您可以使用isNAN()检查它是否是数字 d = isNaN(d) ? 0 : d;

      查看更新的小提琴:https://jsfiddle.net/oed11Lzm/2/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-11-04
        • 2015-12-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多