2016-07-03 113 views
1

我想将div的outerheight()值与另一个div的padding-top值相加。这里是我的功能sumding outerHeight with padding给出错误结果

var headerHeight = $('header').outerHeight() + "px"; 
    console.log(headerHeight); 
    var containerPT = $(".container").css('padding-top'); 
    console.log(containerPT); 
    var totalSpace = (headerHeight + containerPT); 
    console.log(totalSpace); 

,其结果是:

//headerHeight 
474px 
//containerPT 
150px 
//totalSpace 
474px150px 

结果我需要的当然是474 + 150 = 624px; 我通常总结一些东西,我不知道为什么会发生这种情况,我做错了什么。 任何帮助非常感谢。

+0

我更新了答案,检查出来:) –

回答

0

我创建了一个工作演示,你仍然应该解析值。不知何故,jQuery仍将它作为字符串返回,并且还添加了一个替换方法来删除px,以便像从填充顶部那样检索css值。检查以下

var headerHeight = $('header').outerHeight(); 
 
    console.log(headerHeight + "px"); 
 
    var containerPT = $(".container").css('paddingTop').replace(/[^-\d\.]/g, ''); 
 

 
    console.log(containerPT + "px"); 
 
    var totalSpace = (parseInt(headerHeight) + parseInt(containerPT)); 
 
    console.log(totalSpace + "px");
header { height:200px; padding : 20px;} 
 
.container { padding-top: 150px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<header> 
 
    
 
</header> 
 
<div class="container"> 
 
    
 
</div>

+0

这不起作用 – valerio0999

+0

您提供了代码,我只是对其进行了更正。您将“px”添加到变量输出中,这就是为什么它不会添加数字值,而是会附加上,因为该变量将被视为字符串。你能检查你的控制台日志是否有错误?它应该工作,你可能有一个错字,尝试复制粘贴代码;-) –

0

更新的代码我用来获得通过下面的代码你的结果:

HTML代码:

<span id="resultHeight"></span> 
<header></header> 
<div class="container"> 

</div> 

CSS代码:

header{height:474px;} 
.container{height: 150px;} 

jQuery代码:

var headerHeight = parseInt($('header').outerHeight()); 
    console.log(headerHeight); 
    var containerPT = parseInt($(".container").outerHeight()); 
    console.log(containerPT); 
    var totalSpace = (headerHeight + containerPT)+"px"; 
    $("#resultHeight").html(totalSpace); 

请参考以下链接:

Click here

希望它可以帮助你:)

1

你不会得到正确的结果,因为您要添加2串而不是2个数字。 你应该做的是将它们转换为数字以获得正确的结果。为此,请使用parseInt()函数。

var totalSpace = (parseInt(headerHeight) + parseInt(containerPT)); 
console.log(totalSpace + "px"); 

我希望这会给你想要的结果。