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

我有以下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?

最佳答案

好的,您在我写这篇文章时改变了您的问题。本质上,在元素样式的顶部/左侧设置时,需要确保设置了'px'。另外,您不需要parsingInt clientWidth / Height,它们已经是int了(而且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';
}

关于javascript - 如何仅使用JavaScript找出屏幕上的模式对话框的宽度和高度?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19641491/

10-09 22:30