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

标签 javascript onclick height hidden 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";
}

当通过 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/

相关文章:

javascript - Javascript 中的面向对象问题

容器高度上的 CSS "breakpoints"

css - 如果在响应式布局中高于主 block ,如何垂直滚动到 div 旁边?

android - 如何防止 Activity 在按下按钮时加载两次

css - 模态 IFrame 高度

javascript - 尝试使用 ModalService。出现 "ModalService is undefined"错误

javascript - Vue.js - 单文件组件 - 未知的自定义元素

javascript - angularjs ng-click 无法更改 $scope 变量?

javascript - onclick innerhtml 在 onclick innerhtml 中

javascript - 开关 onclick 事件 onclick