让弹出框显示在屏幕中间

时间:2015-08-18 10:26:38

标签: javascript jquery html css

我需要一个框的教程,在屏幕的垂直中间显示一个膨胀作为屏幕的水平中间。

当垂直屏幕尺寸很小时,我当前的尝试有很多失败。

它还需要有回应。任何人都可以指向带有解决方案的教程或代码段。

    function openPopUp( item ) {
    var render_height = $('body').height();
    $('.black_overlay').height(render_height + 'px');
    $('.black_overlay').show();
    $('#popup').show();
    var html ='';
    html += '<h6 class="popup-header">More Information About the Debt</h6>';
    html += '<img src="images/cancel30.png" width="20" height="20" onclick="closePopUp();" style="display:block;margin-top:10px;margin-bottom:10px;margin-left:auto;margin-right:auto;cursor:pointer;">'; 
    html += '<table style="width:100%;">';
    html += '<tr><td>First Name</td><td>' + $(item).attr("hidden-data-dfname") + "</td><tr>";
    html += '<tr><td>Last Name</td><td>' + $(item).attr("hidden-data-dlname") + "</td><tr>";
    html += '</table>';
    $('#popup').html(html);
} // end method openPopUp


function closePopUp() {
    $('#popup').hide();
    $('.black_overlay').hide();
} // end function closePopUp


    <div id="popup">
    </div>  
      <div id="fade" class="black_overlay"></div>

    .black_overlay{
    display: none;
    position: absolute;
    top: 0%;
    left: 0%;
    width: 100%;
    height: 100%;
    background-color: black;
    z-index:1001;
    -moz-opacity: 0.8;
    opacity:.80;
    filter: alpha(opacity=80);
}
#popup {
   position: fixed;
   display: none;
   top: 25%;
   overflow: hidden;
   border: 1px solid #CCC;
   background-color: #F9F9F9;
   border: 1px solid #333;
   width: calc(100% - 42px);
   z-index: 1002;
}
#popup table {
    margin-left:5px;
    margin-right:5px;
    margin-bottom:10px;
}
.popup-header {
    padding:5px;
    background:#006;
    color:#FFF;
    text-align:center;
    width:100%; 
}

2 个答案:

答案 0 :(得分:3)

仅使用这么多css进行div

的水平和垂直居中
#popup {
position: fixed;
top: 50%;
left: 50%;
-webkit-transform: translate(-50%, -50%);
-moz-transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
}

没有JavaScript,没有calc等。无论屏幕大小如何,它都会保留在中心。

答案 1 :(得分:1)

我使用https://jqueryui.com/dialog/#modal-message

解决了问题

你有一个包含你的模态内容的div:

<div style="display: none;" id="terms-of-use-modal"... your dialog html here

然后是一个用响应维度初始化模态的函数:

function init_dialog(){
  var modal_width = $(window).width() - ($(window).width() / 3);
  var modal_height = $(window).height() - 50;

  $("#terms-of-use-modal").dialog({
    modal: true,
    width: modal_width,
    maxHeight: modal_height,
    dialogClass: 'terms-of-use-dialog',
    buttons: {
      Ok: function(){
        $(this).dialog("close");
      }
    }
  });
}

单击该链接将显示模式:

$("#terms-of-use-link").on("click", function(evt){
  evt.preventDefault();
  init_dialog();
});

您也可以在想要模态可见的任何时候使用init_dialog函数。 您可以添加css设置,如:

#terms-of-use-modal { ... }
相关问题