offsetHeight和offsetWidth在第一个onclick事件上计算不正确,而不是第二个

sao*_*yr5 6 javascript height hidden onclick offsetwidth

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

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";
}
Run Code Online (Sandbox Code Playgroud)

当onclick事件调用此函数时,offsetHeight和offsetWidth计算不正确,因此不能正确地对齐元素.如果我第二次单击onclick元素,则offsetHeight和offsetWidth会正确计算.

我试图以我能想象的各种方式改变秩序,这让我发疯!很感谢任何形式的帮助!

mrt*_*man 1

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

老答案 我认为这可以做得更简单。您将顶部和左侧属性设置为 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');
});
Run Code Online (Sandbox Code Playgroud)