0

我有以下 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,但我仍然找不到宽度和高度。

4

1 回答 1

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

于 2013-10-28T13:38:05.973 回答