当前屏幕中间的 JQuery 位置

JQuery position in the middle of current screen

本文关键字:JQuery 位置 中间 屏幕      更新时间:2023-09-26

我正在使用这样的Jquery对话框:

<body>
  <div id="comments_dialog">
   Insert a comment
   <form>
     <input type="text" id="search" name="q">
   </form>
  </div>
....
</body>

dialog = $( "#comment_dialog" ).dialog({
      autoOpen: false,
      height: 400,
      width: 350,
      dialogClass: "flora",
      modal: true,
      buttons: {
        "New Comment": addComment,
        Cancel: function() {
          dialog.dialog( "close" );
        }
      },
      close: function() {
        form[ 0 ].reset();
      }
    });

我的页面是一个包含大量数据的可滚动页面。

问题是对话框显示在页面中间,我希望它

显示在当前屏幕的中间,这样用户就不需要滚动即可看到它。

我该怎么做?

编辑

基于这里的一些解决方案,我将 CSS 设置为像这样修复:

.flora.ui-front {
    z-index: 1000 !important;
     position:fixed !important;
}
.flora.ui-dialog {
    z-index: 1001 !important;
     position:fixed !important;
}

但是,我读到该位置修复了与zIndex的冲突。在这种情况下,我需要将对话框放在当前屏幕的顶部和中间,我该怎么办?

您可能

在 css 中使用了position:absolute;,请尝试将其更改为 position:fixed;

#comment_dialog{
position:fixed;
}

我总是用于我的模态/对话框:

#comment_dialog{
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
}

只要你的div有一个大小(不需要是固定的大小),它就会在窗口中间显示它(水平和垂直居中)

要使用 Jquery 将这些样式动态应用于元素,请使用以下命令:

$("#comment_dialog").css({
    "position" : "fixed",
    "top": "0",
    "left": "0",
    "right": "0",
    "bottom": "0"
});

做一个固定的位置,并对顶部和左侧使用calc函数

#comment_dialog {
  position:fixed;
  left: calc(50% - 200px) !important;
  top: calc(50% - 175px) !important;
}

我认为这对你有帮助

试试这个

dialog = $( "#comment_dialog" ).dialog({
      autoOpen: false,
      height: 400,
      width: 350,
      my: "center",
      at: "center",
      of: window,
      z-index : 9999,
      modal: true,
      buttons: {
        "New Comment": addComment,
        Cancel: function() {
          dialog.dialog( "close" );
        }
      },
      close: function() {
        form[ 0 ].reset();
      }
    });
您可以使用

以下 CSS。

请在"全屏"中运行示例并调整浏览器窗口大小以查看效果。

解释:

  • 对对话框使用 position:fixed,这意味着对话框元素相对于浏览器窗口定位。
  • 使用calc设置位置顶部和左侧,以便执行计算以确定 CSS 属性值。
  • top 的值计算公式为:实际视口高度的 50% 减去一半的对话框高度,因此对话框将始终放置在视口高度的中心。

  • 左侧的值计算公式为:实际视口宽度的 50% 减去一半的对话框宽度,因此对话框将始终放置在视口宽度的中心。

  • 结果是对话框始终位于视口的中心。

#comments_dialog {
  position:fixed;
  top: calc(50vh - 250px/2);
  left: calc(50vw - 350px/2);
  height: 250px;
  width: 350px;
  background-color:yellow;
  z-index: 1000;
}
<div id="comments_dialog">
  Your content here.
</div>

你可以通过这种方式使用 jQuery 获得相同的结果,它会将内联样式添加到您的对话框中:

$("#comments_dialog").css({
  "position": "fixed",
  "top": "calc(50vh - 250px/2)",
  "left": "calc(50vw - 350px/2)",
  "width": "350px",
  "height": "250px",
  "background-color": "yellow",
  "z-index": "1000";
});