jquery动态获取div的高度

时间:2015-05-13 15:48:03

标签: jquery css

我的网站分为两列。

<div id="wrapper">
    <div id="main">
        <div id="center">
           <div class="content">
           <?php
           $page = isset($_GET['page']) ? $_GET['page'] : '';

           switch ($page)
           {
              case "home":
                include("home.php");
              break;

              case "foo":
                include ("foo.php");
              break;

              case "bar":
                include ("bar.php");
              break;
           }
           ?>
           </div>
        </div>
        <div id="sidebar">
            <div class="content">
                 <?php include("block.php");?>
                 <?php include("block2.php");?>
                 <?php include("block3.php");?>
            </div>
        </div>
    </div>
</div>

CSS

#wrapper {
width: 1000px;
margin: 0 auto;
}

#main {
display: table;
}

#center {
width: 720px;
display: table-cell;
background: #fff;
vertical-align: top;
}

#sidebar {
width: 280px;
display: table-cell;
background: #f1f1f1;
vertical-align: top;
}

每当我更改页面时,我会采用div #sidebar或#center的大小index.php?page = foo或index.php?page = bar等等。但结果始终相同

JS

$(function() {

var sidebar = $('#sidebar').css("height");
var center = $('#center').css("height");
console.log("center = " + center + " sidebar = " + sidebar);

/* not work 
$( window ).on("resize", function() {
   sidebar = $('#sidebar').css("height");
   center = $('#center').css("height");
   console.log("center = " + center + " sidebar = " + sidebar);
});*/

});

console.log --> center = 1414px sidebar = 0px

编辑 - 如果我尝试使用.height()

var sidebar = $('#sidebar').height();
var center = $('#center').height();
console.log("center = " + center + " sidebar = " + sidebar);

console.log --> center = 1414 sidebar = -10

我怎样才能正确地获得我的div的高度? 谢谢 古拉爵

3 个答案:

答案 0 :(得分:0)

Jquery为您提供了一个函数height()。 你可以使用

$('elem').height();

找到元素的高度

访问此处获取更多信息jquery height function

jQuery还提供outerHeight()innerHeight()等功能,您可以根据自己的要求使用它们。

答案 1 :(得分:0)

如果你想在窗口调整大小时不断获得div的高度,我建议在jQuery中使用resize事件。

$(window).resize(function () {
    console.log($('#sidebar').height()); 
});

此外,元素的高度函数为您提供高度,它将替换您案例中的css属性。

$('#foo').height()

答案 2 :(得分:0)

string s = System.Text.Encoding.Default.GetString(src.Where(x => x != 0).ToArray()); - 返回元素的高度,不包括填充,边框和边距。

height() - 返回元素的高度,包括填充,但不包括边框和边距。

.innerHeight() - 返回div的高度,包括边框,但不包括边距。

.outerHeight() - 返回div的高度,包括margin。