javascript offsetHeight 和 offsetWidth 在第一个 onclick 事件上计算不正确,而不是第二个
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7404457/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
offsetHeight and offsetWidth calculating incorrectly on first onclick event, not second
提问by saoyr5
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.
当这个函数被 onclick 事件调用时,offsetHeight 和 offsetWidth 计算错误,从而没有正确地居中元素。如果我第二次单击 onclick 元素,则 offsetHeight 和 offsetWidth 计算正确。
I have tried changing the order in every way I can imagine, and this is driving me crazy! Any help is very much appreciated!
我已尝试以我能想象的各种方式更改顺序,这让我发疯了!很感谢任何形式的帮助!
采纳答案by mrtsherman
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/
我猜你的高度和宽度没有在父级上定义。请参阅此小提琴,它可以正常工作。男孩我很聪明。http://jsfiddle.net/mrtsherman/SdTEf/1/
Old AnswerI 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.
旧答案我认为这可以更简单地完成。您将 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');
});