javascript - 在浏览器确定其宽度后获取元素的宽度

标签 javascript jquery css

我有一个弹出框,我希望它完全位于窗口的中央。它具有以下 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 东西可以设置这个元素的 lefttop 属性。

$(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_heightpop_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/

相关文章:

php - 带过滤器的排名系统

javascript - 使用从 BE 获取的数据在弹出窗口上呈现 Reactjs 问题

javascript - jQuery ScrollTo 跳过并且是 Notchy

javascript - 循环遍历 html 元素时替换粘贴中的文本

html - 如何隐藏来自 Angular 区 div 的溢出?

javascript - 将 php 数组引入 javascript 出现意外结果

javascript - 基于值的 Angular 开关不透明度

javascript - Jquery 在 IE7 上崩溃

html - CSS 3 级下拉菜单

Javascript 导致移动导航需要“双击链接才能工作”