【问题标题】:Get sum of margin and height with jQuery使用 jQuery 获取边距和高度的总和
【发布时间】:2013-01-11 15:14:52
【问题描述】:

我想得到另一层的margin-top 大小和height 的总和。

.nav1 的 margin-top 为 30px,.main 的高度为 28px

我使用这个代码:

$('.nav').css('margin-top').replace('px', '') + $('.main').outerHeight()

但我求和的结果是3028

如何计算这两个数字的总和?

【问题讨论】:

  • replace返回的对象是字符串,要转成数字,

标签: jquery css height sum margin


【解决方案1】:

如果您想计算margin-topmargin-bottom 属性,您可以使用outerHeight(true) 为高度添加边距:http://api.jquery.com/outerheight/#outerHeight-includeMargin

var heightWithMargin = $('.main').outerHeight(true);

【讨论】:

  • 这应该是正确的答案。
【解决方案2】:

这是因为您添加了两个字符串,而不是添加了两个整数。试试这个:

var total = parseInt($('.nav').css('margin-top'), 10) + $('.main').outerHeight();

【讨论】:

    猜你喜欢
    • 2014-02-05
    • 2016-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-04
    • 2017-10-21
    • 2011-05-03
    • 1970-01-01
    相关资源
    最近更新 更多