outerHeight() 和 height() 在元素在事件中显示 "display: block" 后给出 0



我正在处理页面的一部分,其中我有4个主div,其中一个div的高度根据其他div的高度计算,而其他div中的一个可能会消失。

<div header></div>
<div divWithCalculatedHeight></div>
<div checkout></div>
<div disappearingDiv></div>

我计算第二个div高度的方法非常简单totalHeight - $header.outerHeight() - $checkout.outerHeight() - $disappearingDiv.outerHeight(),虽然所有div都可见,但它运行得很好。然而,我有一些带有事件的按钮,可以使第四个div消失并再次出现。这是我的问题:

$buttonHide.trigger("hideFourthDiv")
$disappearingDiv.on("hideFourthDiv", () => { 
$disappearingDiv.css({ display: "none" }); 
calculateNew2ndDivHeightAndSetIt();
});

这很好,但再次出现:

$buttonShow.trigger("showFourthDiv")
$disappearingDiv.on("showFourthDiv", () => { 
$disappearingDiv.css({ display: "block" }); // i have also tried with "initial"
console.log($disappearingDiv.outerHeight()); // this here gives 0, so height of 2nd div cant be calculated properly
calculateNew2ndDivHeightAndSetIt();
});

这是我的问题,当我让div重新出现时,仍然在事件中,outerHeight()返回0,我也尝试过使用height(),它也返回0。现在需要注意的是,如果我点击两次按钮,第二次点击它就会起作用,这在某种程度上与我的进一步想法一致:

现在,如果单击buttonShow触发showign事件(仅一次!(,然后我进入浏览器console并手动键入$disappearingDiv.outerHeight(),它确实会给我正确的高度,而不是0!

所以我想,也许,因为我仍然在事件中,在那个时间点上,DOM可能还没有更新,jQuery没有看到";显示";元素,因此考虑到这一点,我在显示div并了解到MutationObserver后,寻找了一种在事件之外触发函数的方法

所以我试着实现它:

const target = $disappearingDiv;
const config = { childList: true, subtree: true};
const callback = () => {console.log($disappearingDiv.height())};
const observer = new MutationObserver(callback);
observer.observe(target, config);

该代码没有被放置在2个事件中的任何一个内;DOMContentLoaded";事件

当我隐藏/显示时,它确实会被触发,但当我第一次点击按钮时,它仍然会给我一个0。

因此,我想我的问题是,一旦disappearingDiv被重新评估,如何从事件的第一次调用中获得它的高度,这样我就不必点击按钮两次。

编辑:我发现了问题所在,但我找不到解决方案,当应用css时,它会内联应用,但浏览器没有重新绘制immediately或其他内容,这就是为什么当我立即检查高度时,它还不可用。我需要等待元素的css更新,然后获取高度。如果我将更新功能放在超时内,它将在低至1毫秒的超时下工作。在这些新发现之后,我打开了一个新问题:当使用JS/Jquery 动态更改时,等待元素的css更新

在检查div的高度之前,可以使用requestAnimationFrame()等待渲染。这将类似于使用setTimeout,但需要等待下一次渲染,而不是等待或n毫秒。

$disappearingDiv.on("showFourthDiv", () => { 
$disappearingDiv.css({ display: "block" }); // i have also tried with "initial"

requestAnimationFrame(() => {
console.log($disappearingDiv.outerHeight()); // this here gives 0, so height of 2nd div cant be calculated properly.
calculateNew2ndDivHeightAndSetIt();
});
});

最新更新