获取div的高度,没有在css中设置高度

Sam*_*pez 87 css jquery height

有没有办法获得元素的高度,如果没有CSS高度规则集为我不能使用的元素.height()jQuery方法因为它需要首先设置CSS规则?有没有其他方法来达到高度?

Sel*_*gam 209

jQuery .height将返回元素的高度.它不需要CSS定义,因为它确定计算的高度.

DEMO

您可以使用.height(),.innerHeight()或者outerHeight()根据您的需要.

在此输入图像描述

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

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

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

.outerHeight(true) - 返回包括边距的div的高度.

请查看以下代码段以获取实时演示.:)

$(function() {
  var $heightTest = $('#heightTest');
  $heightTest.html('Div style set as "height: 180px; padding: 10px; margin: 10px; border: 2px solid blue;"')
    .append('<p>Height (.height() returns) : ' + $heightTest.height() + ' [Just Height]</p>')
    .append('<p>Inner Height (.innerHeight() returns): ' + $heightTest.innerHeight() + ' [Height + Padding (without border)]</p>')
    .append('<p>Outer Height (.outerHeight() returns): ' + $heightTest.outerHeight() + ' [Height + Padding + Border]</p>')
    .append('<p>Outer Height (.outerHeight(true) returns): ' + $heightTest.outerHeight(true) + ' [Height + Padding + Border + Margin]</p>')
});
Run Code Online (Sandbox Code Playgroud)
div { font-size: 0.9em; }
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="heightTest" style="height: 150px; padding: 10px; margin: 10px; border: 2px solid blue; overflow: hidden; ">
</div>
Run Code Online (Sandbox Code Playgroud)


Iam*_*son 35

只是注意以防其他人有同样的问题.

我有同样的问题,并找到了不同的答案.我发现获取高度由其内容决定的div的高度需要在window.load上启动,或者window.scroll不是document.ready否则我得到奇数高度/更小的高度,即在图像加载之前.我也使用了outerHeight().

var currentHeight = 0;
$(window).load(function() {
    //get the natural page height -set it in variable above.

    currentHeight = $('#js_content_container').outerHeight();

    console.log("set current height on load = " + currentHeight)
    console.log("content height function (should be 374)  = " + contentHeight());   

});
Run Code Online (Sandbox Code Playgroud)


Mad*_*ota 10

可以在jQuery中执行此操作.尝试所有选项.height(),.innerHeight().outerHeight().

$('document').ready(function() {
    $('#right_div').css({'height': $('#left_div').innerHeight()});
});
Run Code Online (Sandbox Code Playgroud)

示例截图

在此输入图像描述

希望这可以帮助.谢谢!!


小智 8

还要确保div当前附加到DOM并且可见.

  • 请注意,这可能更适合作为评论而不是答案. (13认同)
  • 他不会有评论特权,放松一下. (4认同)
  • 我认为这是一个重要的信息,因为如果元素没有附加到DOM开始,其他答案都不会起作用. (3认同)