offsetHeight 和 offsetWidth 在第一个 onclick 事件上计算不正确,而不是第二个
我编写了以下脚本来显示隐藏元素,然后将其位置固定到页面的中心。
function popUp(id,type) {
var popUpBox = document.getElementById(id);
popUpBox.style.position = "fixed";
popUpBox.style.display = "block";
popUpBox.style.zIndex = "6";
popUpBox.style.top = "50%";
popUpBox.style.left = "50%";
var height = popUpBox.offsetHeight;
var width = popUpBox.offsetWidth;
var marginTop = (height / 2) * -1;
var marginLeft = (width / 2) * -1;
popUpBox.style.marginTop = marginTop + "px";
popUpBox.style.marginLeft = marginLeft + "px";
}
当 onclick 事件调用此函数时,offsetHeight 和 offsetWidth 计算不正确,因此无法正确使元素居中。如果我第二次单击 onclick 元素,则 offsetHeight 和 offsetWidth 计算正确。
我尝试过以各种我能想象到的方式改变顺序,这让我发疯!非常感谢任何帮助!
I have written the following script to display a hidden element, then fix it's position to the center of the page.
function popUp(id,type) {
var popUpBox = document.getElementById(id);
popUpBox.style.position = "fixed";
popUpBox.style.display = "block";
popUpBox.style.zIndex = "6";
popUpBox.style.top = "50%";
popUpBox.style.left = "50%";
var height = popUpBox.offsetHeight;
var width = popUpBox.offsetWidth;
var marginTop = (height / 2) * -1;
var marginLeft = (width / 2) * -1;
popUpBox.style.marginTop = marginTop + "px";
popUpBox.style.marginLeft = marginLeft + "px";
}
When this function is called by an onclick event, the offsetHeight and offsetWidth are calculated incorrectly, thus not centering the element correctly. If I click the onclick element a second time, the offsetHeight and offsetWidth calculate correctly.
I have tried changing the order in every way I can imagine, and this is driving me crazy! Any help is very much appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我猜你的高度和宽度没有在父级上定义。看看这个小提琴,它工作得很好。孩子,我很聪明。 http://jsfiddle.net/mrtsherman/SdTEf/1/
旧答案< /强>
我认为这可以做得更简单。您将顶部和左侧属性设置为 50%。这将使固定元件稍微偏离中心。我认为您随后尝试使用负边距将其拉回到正确的位置。相反 - 只需从一开始就计算正确的顶部/左侧值,而不必担心边距。这是一个 jQuery 解决方案,但它可以轻松适应纯 js。我还认为如果窗口已滚动,您当前的代码将无法工作。
I am guessing your height and width are not defined on the parent. See this fiddle where it works fine. Boy I'm smart. http://jsfiddle.net/mrtsherman/SdTEf/1/
Old Answer
I think this can be done a lot more simply. You are setting the top and left properties to 50%. This will place the fixed element slight off from the center. I think you are then trying to pull it back into the correct position using negative margins. Instead - just calculate the correct top/left values from the start and don't worry about margin. Here is a jQuery solution, but it can be easily adapted to plain js. I also think your current code won't work if the window has been scrolled at all.