Position a dialog box in center of viewable region of a browser window using javascript/DOM
I need to position a dialog box(read div) in the center of v开发者_如何转开发iewable region of a browser window. I need to use javascript DOM for doing this - making use of scrollHeight, scrollTop, clientHeight, etc. is permissible. The dialog box needs to appear upon clicking a link, it remains invisible otherwise.
CAN'T USE JQUERY TO CREATE A MODAL DIALOG.
Can somebody help me with the centering part of this problem
Regards
(function () {
var getVieportWidth,
getViewportHeight;
if (window.innerWidth) {
// All browsers except IE
getViewportWidth = function() { return window.innerWidth; };
getViewportHeight = function() { return window.innerHeight; };
}
else if (document.documentElement && document.documentElement.clientWidth) {
// IE6 with DOCTYPE
getViewportWidth = function() { return document.documentElement.clientWidth; };
getViewportHeight = function() { return document.documentElement.clientHeight; };
}
else if (document.body.clientWidth) {
// IE4, IE5, IE6 without DOCTYPE
getViewportWidth = function() { return document.body.clientWidth; };
getViewportHeight = function() { return document.body.clientHeight; };
}
var dialogDIVNode = document.getElementById('someID'),
dialogDIVNodeWidth = dialogDIVNode.offsetWidth,
dialogDIVNodeHeight = dialogDIVNode.offsetHeight;
document.getElementById('someLinkID').addEventListener('click', function (e) {
e.preventDefault();
dialogDIVNode.style.left = ( getViewportWidth() / 2 - dialogDIVNodeWidth / 2 ) + 'px';
dialogDIVNode.style.top = ( getViewportHeight() / 2 - dialogDIVNodeHeight / 2) + 'px';
dialogDIVNode.style.display = 'block';
}, false);
}());
Here is how to successfully center a dialog box, regardless of the position in the document:
dialogue.style.left = window.innerWidth - (window.innerWidth - dialogue.offsetWidth) / 2
- dialogue.offsetWidth + pageXOffset;
dialogue.style.top = window.innerHeight - (window.innerHeight - dialogue.offsetHeight) / 2
- dialogue.offsetHeight / 2 + pageYOffset;
精彩评论