【问题标题】:How to center align pop up div using Javascript如何使用Javascript居中对齐弹出div
【发布时间】:2010-07-08 10:16:47
【问题描述】:

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

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

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

【问题讨论】:

    标签: javascript


    【解决方案1】:

    试试这个:

    <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>
    

    CSS 解释: div 是 200x100,您将其放置在距顶部 50% 和距左侧 50% 的位置,但要使其完全居中,您需要从 50% 的值中减去宽度和高度的一半,这样做的方法是使用负边距,因此 margin-top 应该是 height/2 的负值,margin-left 应该是 width/2 的负值。

    【讨论】:

      【解决方案2】:

      只使用 CSS 怎么样:

      <div class="div">Some Content......</div>
      
      .div {
         margin-left: auto;
         margin-right: auto;
      }
      

      【讨论】:

      • 它是一个模态框,有点像 div,我使用了 javascript 的 screen.height 和 screen.width 属性使框居中。但该框到达滚动页面的垂直中心,而不是可见区域的中心
      【解决方案3】:

      尝试:

       function msgBox(message)
       {
        var msgbox = document.getElementById("msgbox");
        msgbox.innerHTML = message;
        var x = (window.innerWidth / 2) - (msgbox.offsetWidth / 2);
        var y = (window.offsetHeight / 2) - (msgbox.offsetHeight / 2);              
        msgbox.style.top = y;
        msgbox.style.left = x;
        msgbox.style.display = "block";
       }
      

      【讨论】:

      • 嗨没有进入中心..可能是一些模组可能会有所帮助..但没有得到它
      • 上面两行代码应该如下: var x = (window.innerWidth / 2) - (msgbox.offsetWidth / 2) + "px"; var y = (window.offsetHeight / 2) - (msgbox.offsetHeight / 2) + "px";这里缺少“px”像素。
      【解决方案4】:

      尝试固定定位:

      #box {
        position: fixed;
        width: 40%;
        margin: 200px 30%;
      }
      

      它只是水平居中。垂直将需要一些玩。我不知道浏览器在垂直对齐方面的行为有何不同。

      【讨论】:

        【解决方案5】:

        我在任何需要滚动的网页上也遇到过垂直居中问题。

        切换到位置:固定解决了它,所以:

        position:fixed;
        top:50%;
        left:50%;
        margin:-50px 0 0 -100px; /* [-(height/2)px 0 0 -(width/2)px] */
        

        这适用于 firefox、google chrome、safari (pc) 和 IE9。

        不幸的是,我希望它出现在 pdf file 前面 - 使用 Firefox、Chrome 时弹出窗口确实出现在前面,但在 IE9 和 Safari 中却落后了......

        【讨论】:

          猜你喜欢
          • 2011-04-01
          • 1970-01-01
          • 1970-01-01
          • 2014-03-03
          • 2013-10-13
          • 2011-03-13
          • 2016-08-17
          • 1970-01-01
          • 2021-01-14
          相关资源
          最近更新 更多