我写了下面的脚本来显示一个隐藏的元素,然后将它的位置固定到页面的中心。
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 计算正确。
我已经尝试用我能想象到的各种方式改变顺序,这让我发疯了!非常感谢任何帮助!
最佳答案
我猜你的高度和宽度没有在父级上定义。看到这个 fiddle 它工作正常。男孩我很聪明。 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');
});
关于javascript - offsetHeight 和 offsetWidth 在第一个 onclick 事件而不是第二个事件上计算不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7404457/