簡體   English   中英

如何阻止Javascript Pop Up移至頁面頂部

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

我單擊了一個按鈕(請參見下圖,並注意滾動條的位置),以便使用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代碼。 您仍然可以使用當前方法隱藏/顯示模態。

PS記住,為上述工作方式提供模態寬度/高度值。

編輯:嘗試將表單放入包裝器中,並使該包裝器成為popup元素,而不是表單。 像這樣:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM