jQuery 和 CSS 将绝对 div 设置到屏幕的中心(检测屏幕的分辨率)

标签 jquery css position

我想创建一个包含登录表单(或其他功能)的新层,并且我想将其显示在屏幕中央(取决于屏幕的分辨率和内容)。

这是代码:

  function new_layer() {
    $('#frameContainer, #showbox').show();
    $('#showbox').load('includes/login.php');
    $(document).ready(function(){
        var hei = eval($(window).height()/2 - $('#showbox > *').outerHeight()/2);
        var wid = eval($(window).width()/2 - $('#showbox > *').outerWidth()/2);
        $('#showbox').css({
          top: hei + "px",
          left: wid + "px"
        }).show();
    });

    // ..................

第一次,它不起作用,文件 login.php 的内容居中 :( ,但是当我点击外部隐藏它,然后再次点击,它起作用了。当刷新页面,问题又出现了。

问题是什么,我该如何解决?

最佳答案

你不需要 JS 计算:

#loginDialog {
    height: 300px;
    width: 400px;
    position: absolute;
    top: 50%;
    left: 50%;
    margin-top: -150px; /* half of the height */
    margin-left: -200px; /* half of the width */
}

关于jQuery 和 CSS 将绝对 div 设置到屏幕的中心(检测屏幕的分辨率),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12265553/

相关文章:

html - 将一个固定的 'arrow' 元素置于另一个固定的 'circle' 元素的中心

javascript - 如何在 div 中包含导入的 css

javascript - jQuery,移动点并获得协调

javascript - 在Javascript中循环遍历Json结构

jquery - 使用 jQuery UI 滚动条的全宽和高度布局

css - rgba 颜色混合 css

ruby - 如何获取字符串中所有出现的模式的索引

jquery - 单击时清除 CSS 菜单悬停状态(通过 ajax 加载页面)

javascript - 响应式 slider 固定背景

html - 将 900px 宽的元素居中,左侧背景为橙色,右侧为白色