gpt4 book ai didi

javascript - 除非调用两次,否则函数无法正确执行

转载 作者:行者123 更新时间:2023-12-02 18:28:21 24 4
gpt4 key购买 nike

一些背景:我使用 JavaScript 将子 div 垂直居中,这些子 div 的高度根据其父 div 中的条件而变化。居中函数如下:

function autoCenter()
{var firstline = document.getElementById("ntext");
var secondline = document.getElementById("dtext");
var l1h = parseInt(getComputedStyle(firstline)["height"]);
var l2h = parseInt(getComputedStyle(secondline)["height"]);
var d1h = parseInt(getComputedStyle(document.getElementById("design"))["height"]);
var d2h = parseInt(getComputedStyle(document.getElementById("design2"))["height"]);
var totalh = l1h + l2h + d1h+ d2h;
document.getElementById("desdiv").style.top = (212-totalh)/2 + "px";
firstline.style.top = (212-totalh)/2 + d1h +"px";
secondline.style.top = (212-totalh)/2 + l1h + d1h + "px";
document.getElementById("desdiv2").style.top = (212-totalh)/2 + l1h + l2h + d1h+ "px";}

ntext、dtext、desdiv 和 desdiv2 是 div。前 2 个根据其中文本的大小而变化,后 2 个根据其中图像的大小而变化(ids design & design 2)

当唯一改变的是文本 div 时,这个函数可以完美地工作。当我更改图像 div 时遇到问题。看起来,涉及 getComputedStyle 的函数的第一部分直到第二次调用该函数时才获得图像的新高度值。在第二次调用之后,一切都像它应该的那样集中。但理想情况下,一切都应该在第一次通话时就可以正常工作。我在这里做错了什么以及如何让 div 在第一次调用时居中?

编辑:我不确定这是否相关,但 autoCenter() 总是从另一个函数中调用。

最佳答案

这很可能是因为您的图像在调用中心函数时尚未完全加载。

向图像添加事件监听器,以便在加载图像时触发中心函数。

至于分号。永远把它们放进去。查找分号插入。

关于javascript - 除非调用两次,否则函数无法正确执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18114491/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com