如何使用Javascript对齐pop up div

Par*_*rag 11 javascript

如何使用javascript将弹出部门与显示器/屏幕中心对齐?

我尝试使用screen.width和screen.height来获得中心.但是分区垂直对齐到滚动页面的中心

提前感谢您的任何帮助和建议

agb*_*gbb 20

试试这个:

<div id="popup" class="popup">
  This a vertically and horizontally centered popup.
</div>

<a onclick="showPopup('popup');">Show Popup</a>

<style type="text/css">
  .popup {
    width:200px;
    height:100px;
    position:absolute;
    top:50%;
    left:50%;
    margin:-50px 0 0 -100px; /* [-(height/2)px 0 0 -(width/2)px] */
    display:none;
  }
</style>

<script type="text/javascript">
  function showPopup(id) {
    var popup = document.getElementById(id);
    popup.style.display = 'block';
  }
</script>
Run Code Online (Sandbox Code Playgroud)

CSS解释: div是200x100,你从顶部定位50%,从左边定位50%,但要让它完全居中,你需要从50%的值中减去宽度和高度的一半,通过这是使用负边距,因此margin-top应该是height/2的负值,margin-left应该是width/2的负值.