如何在px中获得x%的高度?

时间:2012-06-28 16:02:57

标签: jquery css

我给了div一个100%的高度,我想要px的实际高度 我怎样才能找出那个div的高度?

4 个答案:

答案 0 :(得分:6)

使用jquery,当container是div的id时,你可以使用它:

$(document).ready(function() {
    alert($('#container').height());
});

答案 1 :(得分:4)

使用jQuery,您应该可以使用:

$('#div').height();

答案 2 :(得分:2)

如上所述,使用jQuery可以使用:

$(document).ready(function(){
   $("#container").height();
});

请注意jQuery计算height的方式。 引用documentation

  

请注意,.height()将始终返回内容高度,无论如何   CSS box-sizing属性的值。

这意味着,它将忽略您可能已应用的任何边距,填充和边框。

没有人提到您可以获得您感兴趣的确切高度的替代方案如下:

<强> innerHeight()

$(document).ready(function(){
   $("#container").innerHeight();
});

如果您不仅需要元素高度,还要包含任何填充,请使用此选项。

<强> outerHeight()

$(document).ready(function(){
   $("#container").outerHeight(); //Include padding and borders
   $("#container").outerHeight(true); //Include padding, borders and margins
});

如果您不仅需要元素高度,还要包含任何填充,边框和边距(如果将true作为参数传递),请使用此选项。

请参阅DEMO

该演示展示了如何将高度为300px应用于div。此外,css适用于20px的margin-top,50px的padding-top以及5px的边界,这些都会影响总高度。

高度()的演示输出

  

注意jQuery height()如何仍然只返回300像素,   忽略通过css添加到元素的附加高度。

innerHeight()的演示输出

  

注意jQuery innerHeight()如何返回350像素,即300   从div + 50为填充。

outerHeight()的演示输出

  

注意jQuery outerHeight()如何返回360像素,即300   从div + 50为填充+ 10为边界(5底部   和5个顶部)。

outerHeight的演示输出(true)

  

注意jQuery outerHeight(true)如何返回380像素,这就是   div为300,填充为50,边界为10(5   底部和5顶部)+ 20边缘。

答案 3 :(得分:0)

这是一个不使用jquery的解决方案

document.querySelector("#yourElementIdGoesHere").getBoundingClientRect();

此函数将返回具有以下属性的对象

  • 高度
  • 宽度

从那里取宽度和高度,它们以像素为单位

-N