我有一个弹出框,我希望它完全位于窗口的中央。它具有以下 CSS 属性:
#pop_up {
position: fixed;
display: inline-block;
border: 2px solid green;
box-shadow: 0px 0px 8px 5px white;
width: -webkit-max-content;
width: -moz-max-content;
width: max-content;
border-radius: 5px;
background-color: grey;
}
我还有一些 jQuery 东西可以设置这个元素的 left
和 top
属性。
$(document).ready(function() {
window_height = $(window).height();
window_width = $(window).width();
pop_up_height = $('#pop_up').outerHeight();
pop_up_width = $('#pop_up').outerWidth();
pop_up_left = (window_width / 2) - (pop_up_width / 2);
pop_up_top = (window_height / 2) - (pop_up_height / 2);
$('#pop_up').css('left', pop_up_left);
$('#pop_up').css('top', pop_up_top);
});
我让它提醒我所有变量和窗口变量是正确的,但对于 pop_up_height
和 pop_up_width
它会提醒我 '4'
。这显然意味着它只是获得边界。如果我将其更改为 .innerHeight();
和 .innerWidth();
,它会提示 “0”
。因此,它在浏览器根据我的 width: max-content;
属性决定之前返回宽度。试图弄清楚如何在浏览器 auto
之后获取宽度。
此外,当我指定 left
属性时,它是根据边框还是根据元素的实际内部定位元素?所以如果我给一个元素 2px 的边框和 20px 的左边,边框是从左边 20px 还是元素的实际内部?只是一个附带问题。
最佳答案
function popCenter()
{
$('#pop_up').css({'top':($(window).height()-$('#pop_up').height())/2,'left':($(window).width()-$('#pop_up').width())/2});
}
$(document).ready(function() {
popCenter();
})
$(window).resize(function() { //if resize the window, keep the selector in center;
popCenter();
})
关于javascript - 在浏览器确定其宽度后获取元素的宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24566459/