如何将模态div置于屏幕中间?

时间:2013-10-28 13:33:54

标签: javascript modal-dialog

我有以下HTML:

<div class="modal">
   <div class="block-border" style="width: 900px; height: 450px;">
   xxx
   </div>
</div>

我正在尝试这个脚本:

var modal = document.getElementById('modal');
var modal_width = modal.width;
var modal_height = modal.height;
var window_width = window.width;
var window_height = window.height;
modal.style.left = window_width / 2 - modal_width / 2;
modal.style.top = window_height / 2 - modal_height / 2;

当我检查模态变量时,它看起来是正确的。但是modal_width和modal_height变量显示未定义。我尝试将宽度和高度样式移动到第一个div,但我仍然找不到宽度和高度。

1 个答案:

答案 0 :(得分:1)

当然你可以:

function setmodal()
{
  var modal_width = $('.modal').width(),
  window_width = window.width;
  $('.modal').css('left', window_width/2 - modal_width/2);  
}
window.onresize = function(){
    setmodal();
}
$(function(){
 setmodal();
});

Javascript:

function setmodal()
{
  var modal = document.getElementsByClassName('modal')[0],
  modal_width = modal.width,
  window_width = window.width;
  modal.style.left = window_width/2 - modal_width/2;    
}
window.onresize = function(){
    setmodal();
}

唯一的缺点是IE 8和&lt;

中的支持