如果某个元素没有设置 CSS 高度规则,那么有没有办法获取该元素的高度?由于需要先设置 CSS 规则才能使用 .height()
jQuery 方法,所以我不能使用它。还有其他方法可以获得高度吗?
jQuery .height
方法会返回元素的高度,不需要CSS定义,因为它确定了计算后的高度。
你可以根据需求使用.height()
, .innerHeight()
或 outerHeight()
方法。
.height()
- 返回元素的高度,不包括padding、border和margin。
.innerHeight()
- 返回元素的高度,包括padding但不包括border和margin。
.outerHeight()
- 返回div的高度,包括border但不包括margin。
.outerHeight(true)
- 返回div的高度,包括margin。
查看下面的代码片段以获得实时演示。 :)
$(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>')
});
div { font-size: 0.9em; }
<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>
如果有其他人遇到同样的问题,这里提供一点提示。
我也遇到了同样的问题,并找到了不同的答案。我发现,获取高度由其内容确定的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());
});
可以在jQuery中完成此操作。尝试所有选项.height()
、.innerHeight()
或.outerHeight()
。
$('document').ready(function() {
$('#right_div').css({'height': $('#left_div').innerHeight()});
});
示例截图
希望这能有所帮助。谢谢!
同时确保 div已经被添加到DOM中并且是可见的。
height()
需要有一个 CSS 规则? - James Montagneheight()
将获取元素的计算高度... - elclanrsheight
没有CSS设置的要求。那个链接与jQuery无关。 - James Montagne