【问题标题】:jQuery calculating 2 different HTML element attributes (height + margin-bottom)jQuery 计算 2 个不同的 HTML 元素属性(高度 + 边距底部)
【发布时间】:2014-07-01 14:24:50
【问题描述】:

我正在尝试获取元素的高度和边距底部,并计算它们。但到目前为止,我只能这样做:

var sum = $('div').height() + 25); 

25 我不得不在

的样式表中查找自己
div {
   height: 75px;
   margin-bottom: 25px;
}

我怎样才能自动做到这一点?

因为当我尝试时:

var sum = $('div').height() + $('div').css('margin-bottom'); 

它没有返回任何值。

【问题讨论】:

标签: javascript jquery html css


【解决方案1】:

您可能正在寻找http://api.jquery.com/outerheight/,其中包括边距、填充和边框(所有这些都计入总高度以及基本高度)。或者,您可以使用parseInt($('div').css('margin-bottom')),因为该值是一个看起来像这样的css 字符串:100pxparseInt() 将从该 css 中提取 100,这正是您想要的。

此外,总的来说,你做错了。您是否在寻找所有 div 元素的所有高度的总和?还是您的页面只有一个 div?

【讨论】:

  • 仅供参考:如果你想总结所有divs 的height()s(或outerHeight()s),你应该看看jquery的eachapi.jquery.com/each
【解决方案2】:

文档中有很多“div”元素(通常)。 你需要一个更好的选择器来选择你想要的。 Fiddle for value in console.log

<div id="TestId" class="test"></div>

.test
{
height:40px;
margin:5px;
}

var tester = $("#TestId");
var eleHeight = tester.outerHeight();
var marginBottomHeight = tester.css('margin-bottom').replace("px", "")
console.log(eleHeight + parseInt(marginBottomHeight));    

【讨论】:

  • 这是一个例子... :P
【解决方案3】:

$('div').css('margin-bottom') 将附加 px。尝试使用类似parseInt()

var sum = $('div').height() + parseInt($('div').css('margin-bottom'), 10); 

W

【讨论】:

    猜你喜欢
    • 2015-11-07
    • 1970-01-01
    • 2011-04-27
    • 1970-01-01
    • 1970-01-01
    • 2013-11-27
    • 2011-05-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多