Javascript-форум (https://javascript.ru/forum/)
-   Элементы интерфейса (https://javascript.ru/forum/dom-window/)
-   -   Вычислить длину модального окна (https://javascript.ru/forum/dom-window/67713-vychislit-dlinu-modalnogo-okna.html)

shyxeroks 04.03.2017 12:53

Вычислить длину модального окна
 
Приветствую. Возник вопрос, возможно ли вычислить длину модального окна до его появления, для того что-бы размещать всегда по центру экрана в видимой области, так как длина всегда разная. Или по средствам css возможно?
<style>
/******************** Modal ******************/
#modal_form {
	width: 500px; 
	border-radius: 5px;
	border: 3px #000 solid;
	background: #fff;
	position: fixed;  
	left: 50%; 
	margin-left: -250px; 
	display: none; 
	opacity: 0; 
	z-index: 5; 
	padding: 5px;
	border:3px solid #b88c27;
	color:#b88c27;
}
#modal_form #modal_close {
	background: #b88c27;
	color: #FFFFFF;
	line-height: 25px;
	position: absolute;
	right: -12px;
	text-align: center;
	top: -10px;
	width: 24px;
	text-decoration: none;
	font-weight: bold;
	-webkit-border-radius: 12px;
	-moz-border-radius: 12px;
	border-radius: 12px;
	-moz-box-shadow: 1px 1px 3px #000;
	-webkit-box-shadow: 1px 1px 3px #000;
	box-shadow: 1px 1px 3px #000;
	cursor:pointer;
}
#modal_form #modal_close:hover {background: red;}
#modal_overlay {/*подложка */
	z-index: 3; 
	position: fixed; 
	background-color: #000; 
	opacity: 0.8;
	width: 100%; 
	height: 100%;
	top: 0; 
	left: 0; 
	cursor: pointer;
	display: none; 
}
</style>
Вызывается так:
<script>
function show_notice(text,color){
$('#modal_overlay').fadeIn(400,function(){ 
$('#modal_form').css({'display':'block', 'border-color':color}).animate({opacity: 1, top: '50%'}, 200);
$('#modal_text_add').html(text).css('color',color);
});
}
</script>

Благодарю за информацию!

laimas 04.03.2017 13:26

Что значит длину, может ширину, а это что width: 500px?

margin-left: -250px;

shyxeroks 04.03.2017 13:33

Height интересует. Например, что такое в css добавить top:50%. Скриптом определить height окна и добавить margin-top: - длина окна /2

laimas 04.03.2017 14:09

Цитата:

Сообщение от shyxeroks
Например, что такое в css добавить top:50%.

max-height: проценты. От него top:50%, margin-top: -50%;

рони 04.03.2017 15:13

shyxeroks,
<!DOCTYPE html>

<html>
<head>
  <title>Untitled</title>
  <meta charset="utf-8">
  <style type="text/css">
  </style>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

  <script>
$(function() {

});
  </script>
</head>

<body>
<div id="modal_form"><div id="modal_text_add"></div></div>
<div id="modal_overlay"></div>
<style>
/******************** Modal ******************/
#modal_form {
  width: 500px;
  border-radius: 5px;
  border: 3px #000 solid;
  background: #fff;
  position: absolute;
  display: none;
  opacity: 0;
  z-index: 5;
  padding: 5px;
  border:3px solid #b88c27;
  color:#b88c27;
  top:0;
  transition: all .8s linear;

}
#modal_form #modal_close {
  background: #b88c27;
  color: #FFFFFF;
  line-height: 25px;
  position: absolute;
  right: -12px;
  text-align: center;
  top: -10px;
  width: 24px;
  text-decoration: none;
  font-weight: bold;
  border-radius: 12px;
  -moz-box-shadow: 1px 1px 3px #000;
  box-shadow: 1px 1px 3px #000;
  cursor:pointer;
}
#modal_form #modal_close:hover {background: red;}
#modal_overlay {/*подложка */
  z-index: 3;
  position: fixed;
  background-color: #000;
  opacity: 0.8;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  cursor: pointer;
  display: none;
}


</style>
Вызывается так:
<script>
jQuery.fn.center = function()
  {
  var w = $(window);
    this.css({"top":(w.height()-this.height())/2+w.scrollTop() + "px",
  	"left":(w.width()-this.width())/2+w.scrollLeft() + "px" });
    return this;
  }


function show_notice(text,color){
$('#modal_overlay').fadeIn(400,function(){
$('#modal_form').css({'display':'block', 'border-color':color,opacity: 1})
$('#modal_text_add').html(text).css({'color':color});
$('#modal_form').center()
});
}
show_notice("Lorem ipsum dolor sit amet,<br> consectetur adipiscing elit.<br> Sunt enim prima elementa naturae,<br> quibus auctis vírtutis quasi germen efficitur.","#0000FF")
</script>

</body>
</html>

shyxeroks 04.03.2017 16:58

рони,
Благодарю то, что нужно. Еще такой вопрос. Хочу отключить скролл у body,html - $("body,html").css('overflow', 'hidden');но происходит сдвиг, так как полоса прокрутки пропадает, у всех браузеров ширина скрол бар разная, возможно ли кроссбраузерно определить ширину и в момент отключения скролла просто сдвинуть в лево.
То есть примерно как то так?
$("body,html").css({'overflow': 'hidden','padding-right': 'ширина скролл бара px'});

Но опять же, если так двигать, то смещается и фон.
Еще возник вопрос по поводу закрытия модального окна, сейчас код такой:
function show_notice_exit(){
$('#modal_form').animate({opacity: 0}, 200,function(){
$('#modal_form').css('display', 'none').removeAttr('style');
$('#modal_overlay').fadeOut(400);
$('#modal_text_add').html('').removeAttr('style');
}
);
}

Почему то рывком закрывается.

shyxeroks 04.03.2017 17:16

С рассчетом ширины полосы прокрутки разобрался, окей гугл:
function getScrollBarWidth () {
    var inner = document.createElement('p');
    inner.style.width = '100%';
    inner.style.height = '200px';

    var outer = document.createElement('div');
    outer.style.position = 'absolute';
    outer.style.top = '0px';
    outer.style.left = '0px';
    outer.style.visibility = 'hidden';
    outer.style.width = '200px';
    outer.style.height = '150px';
    outer.style.overflow = 'hidden';
    outer.appendChild (inner);

    document.body.appendChild (outer);
    var w1 = inner.offsetWidth;
    outer.style.overflow = 'scroll';
    var w2 = inner.offsetWidth;
    if (w1 == w2)
        w2 = outer.clientWidth;
    document.body.removeChild (outer);

    return (w1 - w2);
};

Попробовал в опере, яндекс и мозила, нормально рывка нет. Со смещением фона, то же разобрался, по этому поводу вопрос снят, остался только по поводу закрытия модального окна.

рони 04.03.2017 17:47

центрирование модального окна
 
shyxeroks, функция закрытия
<!DOCTYPE html>

<html>
<head>
  <title>Untitled</title>
  <meta charset="utf-8">
  <style type="text/css">
  body{
    height: 2000px;
  }
  /******************** Modal ******************/
#modal_form {
  width: 500px;
  border-radius: 5px;
  border: 3px #000 solid;
  background: #fff;
  position:  fixed;
  display: none;
  opacity: 0;
  z-index: 5;
  padding: 5px;
  border:3px solid #b88c27;
  color:#b88c27;
  top:0;
  transition: all .8s linear;

}
#modal_form #modal_close {
  background: #b88c27;
  color: #FFFFFF;
  line-height: 25px;
  position: absolute;
  right: -12px;
  text-align: center;
  top: -10px;
  width: 24px;
  text-decoration: none;
  font-weight: bold;
  border-radius: 12px;
  -moz-box-shadow: 1px 1px 3px #000;
  box-shadow: 1px 1px 3px #000;
  cursor:pointer;
}
#modal_form #modal_close:hover {background: red;}
#modal_overlay {/*подложка */
  z-index: 3;
  position: fixed;
  background-color: #000;
  opacity: 0.8;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  cursor: pointer;
  display: none;
}


  </style>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

  <script>
$(function() {
jQuery.fn.center = function() {
    var w = $(window);
    this.css({
        "top": (w.height() - this.height()) / 2  + "px",
        "left": (w.width() - this.width()) / 2  + "px"
    });
    return this
};

function scrollWidth() {
    var div = document.createElement("div");
    div.style.overflowY = "scroll";
    div.style.width = "50px";
    div.style.height = "50px";
    div.style.visibility = "hidden";
    document.body.appendChild(div);
    var width = div.offsetWidth - div.clientWidth;
    document.body.removeChild(div);
    return width
}

function show_notice(text, color) {
    $("body,html").css({
        "overflow": "hidden",
        "padding-right": scrollWidth() + "px"
    });
    $("#modal_overlay").fadeIn(400, function() {
        $("#modal_form").css({
            "display": "block",
            "border-color": color,
            opacity: 1
        });
        $("#modal_text_add").html(text).css({
            "color": color
        });
        $("#modal_form").center()
    })
}
show_notice("Lorem ipsum dolor sit amet,<br> consectetur adipiscing elit.<br> Sunt enim prima elementa naturae,<br> quibus auctis v\u00edrtutis quasi germen efficitur.", "#0000FF");

function show_notice_exit() {
    $("#modal_form").css({
        opacity: 0,
        top: 0
    });
    $("#modal_overlay").fadeOut(400, function() {
        $("body,html").css({
            "overflow": "auto",
            "padding-right": ""
        });
        $("#modal_form").css({
        "display": "none"
    });
    })
}
window.setTimeout(show_notice_exit, 3E3);
window.setTimeout(function() {
    show_notice("<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fatebuntur Stoici haec omnia dicta esse praeclare, neque eam causam Zenoni desciscendi fuisse. Dolor ergo, id est summum malum, metuetur semper, etiamsi non aderit; <i>Recte, inquit, intellegis.</i> </p>", "#FF0000")
}, 7E3);
window.setTimeout(show_notice_exit, 12E3);
});
  </script>
</head>

<body>
<div id="modal_form"><div id="modal_text_add"></div></div>
<div id="modal_overlay"></div>

</body>
</html>

shyxeroks 07.03.2017 11:33

рони, благодарю, то что нужно.

laimas 07.03.2017 14:40

Цитата:

Сообщение от shyxeroks
$("body,html").css({'overflow'

Лучше так, $("html").css({\'overflow\' или возможно столкнуться проблемами при использовании некоторых плагинов.


Часовой пояс GMT +3, время: 10:56.