如何阻止Javascript Pop Up移动到页面顶部

How to stop Javascript Pop Up from moving to the top of the page

本文关键字:顶部 移动 Up 何阻止 Javascript Pop      更新时间:2023-09-26

我有一个按钮被单击(见下图并注意滚动条的位置),以便使用 Javascript 弹出一个div 弹出窗口。

见图:https://docs.google.com/file/d/0B1O3Ee_1Z5cRTko0anExazBBQkU/preview

当我单击按钮时,它会在页面的最顶部弹出弹出窗口。

查看图片 : https://docs.google.com/file/d/0B1O3Ee_1Z5cRWjFPS0xEV0tTeFk/preview

我希望弹出窗口居中出现,当我单击按钮时,页面滚动到的确切位置。

这是我的代码。任何帮助将不胜感激!谢谢!

.JS:

$(document).ready(function(){
//open popup
$("#pop").click(function(){
  $("#overlay_form").fadeIn(1000);
  positionPopup();
});
//close popup
$("#close").click(function(){
    $("#overlay_form").fadeOut(500);
});
});
//position the popup at the center of the page
function positionPopup(){
  if(!$("#overlay_form").is(':visible')){
    return;
  } 
  $("#overlay_form").css({
      left: ($(window).width() - $('#overlay_form').width()) / 2,
      top: ($(window).width() - $('#overlay_form').width()) / 7,
      position:'absolute'
  });
}
//maintain the popup at center of the page when browser resized
$(window).bind('resize',positionPopup);

.HTML:

              <a href="#" id="pop" ><li style="float:right; margin-left:5px; list-style-type:none; line-height:0px; padding-top:20px;"><i class="fa fa-share-square fa-lg"></i></li></a>
              <br />
<form id="overlay_form" style="display:none">
        <a href="#" id="close" >Close</a>
    <h2> Hello, World.</h2>
    Share buttons here :-)
</form>
您是否有

理由使用 JS 而不是 CSS 来定位弹出窗口?

您可以简单地将模式设置为:

#overlay_form {
  position: fixed;
  top: 50%;
  left: 50%;
  margin-top: -00px;  /* 1/2 the height of the modal */
  margin-left: -00px; /* 1/2 the width of the modal */
}

此方法不需要为每次调整大小调用 JS 代码。您仍然可以使用当前方法隐藏/显示模态。

附言:请记住为您的模态提供上述工作方法的宽度/高度值。

编辑:尝试将表单放入包装器中,并使该包装器成为弹出元素,而不是表单。这样:

.HTML

<div class="pop-up">
    <form id="overlay_form">
        <a href="#" id="close" >Close</a>
        <h2> Hello, World.</h2>
        Share buttons here :-)
    </form>
</div>

.CSS

.pop-up {
  position: fixed;
  width: 300px;   /* set this to whatever you want */
  height: 150px;  /* set this to whatever you want */
  top: 50%;
  left: 50%;
  margin-top: -75px;  /* 1/2 the height of the modal (150 / 2) */
  margin-left: -150px; /* 1/2 the width of the modal (300 / 2) */
}

JSFiddle