我在一个页面上有两个并排的元素。一个元素具有固定大小 (100vh) - .hero-half - 另一个元素具有可变长度的文本 - .project-details。当流体文本容器扩展为高于图像容器时,我想对其应用一个类,将其子元素之一的高度限制为将总文本容器高度重新与图像高度相等。
HTML:
<div class="project-details left">
<h1 class="project">Title</h1>
<div class="project-summary">
<div class="summary-container">
<p>A bunch of paragraphs here</p>
</div>
<a class="more" href="#">More</a>
<a class="less" href="#">Less</a>
</div>
</div>
<div class="hero hero-half right" style="background-image: url('/img/placeholder-vert1.jpg')"></div>
相关的CSS:
.hero-half {
width: 50%;
height: 100vh;
}
.project-details {
width: 50%;
height: auto;
}
.project-summary .summary-container {
overflow: hidden;
&.restrict-height {
.summary-container {
// set max height
max-height: calc(100vh - 615px);
}
}
}
这是我的 JS 代码:
$(function () {
var bpTab = 1024;
resize = function() {
var winWidth = $(window).width();
var heroHeight = $(".hero-half").outerHeight();
var boxHeight = $(".project-details").outerHeight();
var $box = $(".project-summary");
if ( boxHeight > heroHeight && winWidth > bpTab) {
// if on desktop layout AND if text is pusing box too big, restrict box height
$box.addClass("restrict-height");
} else {
// if not on desktop or text is not pushing box too big
$box.removeClass("restrict-height");
$box.removeClass("is-expanded");
};
};
// resize on window resize
$(window).bind("resize orientationchange", function(){
resize();
});
// resize on page load
resize();
});
因此,当 project-details div 的高度高于 .hero-half 时,它会添加一个为其中一个孩子设置 max-height 的类,这会使 .project-details 的总高度回到等于或小于 .英雄一半。
但是,当我调整窗口大小以强制文本将项目详细信息高度推得太高并触发限制高度类时,它仅在屏幕宽度和高度加起来为偶数时才有效(宽度和高度都是偶数,或两者都是奇数)。如果总数是奇数,则项目详细信息的 outerHeight 似乎计算不正确。
我认为,问题在于 .project-details 的 outerHeight 有时是在它限制的文本高度之前的自然高度计算的,有时它是在应用该类之后和限制的文本高度之后计算的,因此将 .project-details 高度降低到可接受的范围内。
我尝试为添加类添加超时延迟,希望额外的时间意味着 outerHeight 计算始终正确,但这并没有什么不同。
我应该如何更改此 JS 代码以确保 .project-details outerHeight 始终在应用 restrict-height 类之前读取高度?
和相关:为什么奇数像素尺寸在这里有任何影响?