我试图找出我正在使用的模态对话框的宽度和高度:
我有以下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?
答案 0 :(得分:2)
好的,你在我写这篇文章时改变了你的问题。基本上,您需要确保在元素的样式上设置顶部/左侧时设置'px'
。此外,您不需要解析clientWidth / Height,它们已经是整数(并且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';
}