Как мне центрировать javascript css popup div, независимо от разрешения экрана?
У меня есть следующий код, который открывает новое всплывающее окно при отключении фона, проблема в том, что я должен позиционировать это так, чтобы он был 100px сверху (уже получил это через CSS #dialog), а также в центре экрана, независимо от разрешения пользователя?
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<script type="text/javascript">
function showPopUp(el) {
var cvr = document.getElementById("cover")
var dlg = document.getElementById(el)
cvr.style.display = "block"
dlg.style.display = "block"
if (document.body.style.overflow = "hidden") {
cvr.style.width = "1024"
cvr.style.height = "100%"
}
}
function closePopUp(el) {
var cvr = document.getElementById("cover")
var dlg = document.getElementById(el)
cvr.style.display = "none"
dlg.style.display = "none"
document.body.style.overflowY = "scroll"
}
</script>
<style type="text/css">
#cover {
display: none;
position: absolute;
left: 0px;
top: 0px;
width: 100%;
height: 100%;
background: gray;
filter: alpha(Opacity = 50);
opacity: 0.5;
-moz-opacity: 0.5;
-khtml-opacity: 0.5
}
#dialog {
display: none;
left: 100px;
top: 100px;
width: 300px;
height: 300px;
position: absolute;
z-index: 100;
background: white;
padding: 2px;
font: 10pt tahoma;
border: 1px solid gray
}
</style>
</head>
<body>
<div id="cover"></div>
<div id="dialog">
My Dialog Content
<br><input type="text">
<br><input type="button" value="Submit">
<br><a href="#" onclick="closePopUp('dialog');">[Close]</a>
</div>
<a href="#" onclick="showPopUp('dialog');">Show</a>
</body>
</html>
Ответы
Ответ 1
Основанное на CSS решение для центра:
Вам нужно использовать эти стили, чтобы они выглядели мертвыми:
position:absolute;
top:50%;
left:50%;
width:400px; /* adjust as per your needs */
height:400px; /* adjust as per your needs */
margin-left:-200px; /* negative half of width above */
margin-top:-200px; /* negative half of height above */
Значит position
. top
и left
должны быть 50%
. margin-left
и margin-top
должны быть отрицательными на половину ширины и высоты окна соответственно.
Обратите внимание, что если вы хотите, чтобы ваше всплывающее окно отображалось в центре, даже если страница прокручивается, вам придется использовать position:fixed
вместо обратного вывода, чтобы он не работал в IE6.
Ответ 2
То, что вам нужно, называется light-box.
Чтобы создать его, вы должны изменить код HTML, CSS и JS.
Скажем, ваш лайтбокс состоит только из строки "форма входа". (Вы можете поместить все, что хотите там) Код HTML должен выглядеть так:
<div id = "loginBox">login form</div>
Теперь нам нужно скрыть его с помощью CSS:
div#loginBox {
display: none;
}
Теперь наш ящик не виден. Давайте изменим наш ящик, как вы хотите, чтобы он был 100px сверху:
div#loginBox {
display: none;
top: 100px;
}
Мы будем беспокоиться об отключении фона позже.
Наша следующая задача - создать кнопку, которая отобразит поле, когда оно нам понадобится. Easy-Peasy:
<div id = "loginBox" >login form</div>
<a id = "displayButton">login</a>
Обратите внимание, что нам не нужен атрибут "href", потому что он будет перемещать экран при нажатии и другом нежелательном поведении.
Пусть присоединяет обработчик событий на кнопке через JS:
var IE = document.all ? true : false; // obligatory "browser sniffing"
function display_box() {
document.getElementsById("loginBox").style.display = "inline-block"; // or "inline"
}
window.onload = function() {
var login_box = document.getElementsById("loginBox");
if (!IE) {
login_box.addEventListener( "click", display_box , false );
}
else {
login_box.attachEvent( "onclick", display_box );
}
}
Но вы хотите, чтобы он находился в центре экрана? Тогда функция будет выглядеть так:
function display_box() {
var theBox = document.getElementsById("loginBox").style,
left = document.width / 2 - 50; // 150 because it is 300 / 2
theBox.display = "inline-block";
theBox.left = left.toString() + "px";
}
Я бы предположил, что вам нужно закрыть окно в какой-то момент и сделать эффект "отключенного фона". Для этого вы можете создать div-класс, который распространяется на весь экран, прикрепить к нему событие "display", поместить некоторый z-index в css, чтобы убедиться, что loginBox находится над "отключенным фоном", и присоедините "закрыть событие loginBox" на "background" div. И вот окончательный код выглядит следующим образом:
Обратите внимание, что мы заботимся только о размещении кнопки входа в систему, потому что другие скрыты от представления, а затем изменены JS:
HTML:
<div id = "loginBox" >login</div>
<a id = "displayButton">login</a>
<div id = "backgroundDarkener"> </div>
CSS
div#loginBox {
display: none;
top: 100px;
width: 300px; #it is important to know the width of the box, to center it correctly
z-index: 2;
}
div#backgroundDarkener {
background: #000;
display: none;
position: fixed;
top: 0px;
left: 0px;
width: 100%;
height: 100%;
z-index: 1;
opacity: 0.8;
# needless to say, you should play with opacity or if you want your
# css to validate - background image (because I suspect it won't
# validate for old versions of IE, Safari, etc.) This is just a suggestion
}
JS:
var IE = document.all ? true : false; // obligatory "browser sniffing"
function display_box() {
var theBox = document.getElementsById("loginBox").style,
background = document.getElementsById("loginBox").style,
left = document.width / 2 - 150; // 150 is 300 / 2
theBox.display = "inline-block";
theBox.left = left.toString() + "px";
background.display = "inline-block";
}
function hide_box() {
document.getElementsById("loginBox").style.display = "none";
document.getElementsById("backgroundDarkener").style.display = "none";
}
window.onload = function() {
var login_box = document.getElementsById("loginBox"),
background = document.getElementsById("backgroundDarkener");
if (!IE) {
login_box.addEventListener( "click", display_box , false );
background.addEventListener( "click", hide_box , false );
}
else {
login_box.attachEvent( "onclick", display_box );
background.attachEvent( "onclick", hide_box );
}
}
Ответ 3
Быстрый поиск Google this;
function PopupCenter(pageURL, title,w,h) {
var left = (screen.width/2)-(w/2);
var top = (screen.height/2)-(h/2);
var targetWin = window.open (pageURL, title, 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width='+w+', height='+h+', top='+top+', left='+left);
}
Ответ 4
Здесь flexbox появляется спасение!
.parent {
display: flex;
height: 300px; /* Or whatever */
}
.child {
width: 100px; /* Or whatever */
height: 100px; /* Or whatever */
margin: auto; /* Magic! */
}
Ответ 5
Простой, margin: 100px auto;
. Нет необходимости делать вычисления в JavaScript.
Живой пример
Ответ 6
Просто сделайте следующее:
.body {
position: relative;
}
.popup {
position: absolute;
max-width: 800px;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
не имеет значения для экрана или всплывающего окна. Это будет центрировать <div class="popup"></div>
.
Ответ 7
Вам нужно использовать эти стили для создания div-центра:
width:500px;
left:0;
right:0;
margin:0 auto;