【问题标题】:offsetHeight and offsetWidth calculating incorrectly on first onclick event, not secondoffsetHeight 和 offsetWidth 在第一个 onclick 事件上计算不正确,而不是第二个
【发布时间】:2011-11-16 07:05:39
【问题描述】:

我编写了以下脚本来显示隐藏元素,然后将其位置固定到页面中心。

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 计算正确。

我尝试了各种我能想象到的改变顺序,这让我发疯了!非常感谢任何帮助!

【问题讨论】:

  • 嗯,您的代码对我来说似乎可以正常工作? jsfiddle.net/mrtsherman/SdTEf/1
  • @mtrsherman,谢谢。你是 jsfiddle 向我展示了我的方式的错误。请注意:如果您没有为要确定其高度和宽度的元素定义高度和宽度,则使用 offsetHeight 和 offsetWidth 将无法获得正确的高度和宽度。
  • 是的。很高兴你解决了。像这样的问题,看起来一切正常,但实际上并非如此——让我的脑袋想爆炸!
  • 如果您将其发布为答案,我肯定会选中它!

标签: javascript onclick height hidden offsetwidth


【解决方案1】:

我猜你的高度和宽度没有在父母身上定义。看看这个小提琴,它工作正常。男孩,我很聪明。 http://jsfiddle.net/mrtsherman/SdTEf/1/

旧答案 我认为这可以更简单地完成。您将 top 和 left 属性设置为 50%。这将使固定元素稍微偏离中心。我认为您正在尝试使用负边距将其拉回正确的位置。相反 - 只需从一开始就计算正确的顶部/左侧值,而不必担心边距。这是一个 jQuery 解决方案,但它可以很容易地适应纯 js。我还认为,如果窗口完全滚动,您当前的代码将无法工作。

//this code will center the following element on the screen
$('#elementid').click(function() {
    $(this).css('position','fixed');
    $(this).css('top', (($(window).height() - $(this).outerHeight()) / 2) + $(window).scrollTop() + 'px');
    $(this).css('left', (($(window).width() - $(this).outerWidth()) / 2) + $(window).scrollLeft() + 'px');
});

【讨论】:

  • 你是对的,你的方式会起作用(我测试它以确保 offsetHeight 和 offsetWidth 是正确的),除了你不能调整窗口大小并且让 div 完全居中,这是什么我在寻找。我真的最感兴趣的是为什么我的 offsetHeight 和 offsetWidth 没有给我正确的数字,因为我一直使用这种 css 技术,它总是给我想要的效果。
  • 啊,我现在明白了。我赞成你的问题,所以希望有人能给你一个更好的答案。您可以将上述内容绑定到$(window).resize() 事件,但您的方法肯定更优雅。
猜你喜欢
  • 2017-05-31
  • 1970-01-01
  • 1970-01-01
  • 2017-07-29
  • 1970-01-01
  • 2021-06-20
  • 2016-10-20
  • 2018-10-12
  • 1970-01-01
相关资源
最近更新 更多