1

我试图找出我正在使用的模式对话框的宽度和高度:

我有以下 HTML:

<div data-ng-show="modal.visible" id="modal" style="height: 300px; width: 900px;">
   <div class="block-border">
     xxx
   </div>
</div>

我有以下脚本:

$scope.openModal = function ($scope) {  
   var modal = document.getElementById('modal');
   var modal_width = modal.offsetWidth
   var modal_height = modal.offsetHeight;
   var modal_width = parseInt(modal.width, 10)
   var modal_height = parseInt(modal.height, 10)
   var window_width = window.innerWidth;
   var window_height = window.innerHeight;
   modal.style.left = window_width / 2 - modal_width / 2;
   modal.style.top = window_height / 2 - modal_height / 2;
   $scope.modal.visible = true;

到目前为止,我获得模态高度和宽度的两种类型的检查似乎都没有工作,我不知道如何获得 modal_width 和 modal_height ?

4

1 回答 1

3

好的,你在我写的时候改变了你的问题。本质上,您需要确保'px'在设置元素样式的顶部/左侧时进行设置。此外,您不需要解析客户端宽度/高度,它们已经是整数(而且,modal.width/height 不可用)。这是一个工作功能,假设您的模式已经在屏幕上:

function () {  
  // First, I'm assuming the modal is currently on the screen
  // and not display:none, or visibility:hidden. Otherwise
  // we cannot calculate the dimensions
  var modal = document.getElementById('modal');
  var modal_width = modal.offsetWidth
  var modal_height = modal.offsetHeight;
  var window_width = window.innerWidth;
  var window_height = window.innerHeight;
  modal.style.left = Math.round(window_width / 2 - modal_width / 2)+'px';
  modal.style.top = Math.round(window_height / 2 - modal_height / 2)+'px';
}
于 2013-10-28T17:48:30.480 回答