Название документа

Как сделать — Модальное окно

Узнать, как создать модальное окно с помощью CSS и JavaScript.

Создать модальное окно

Модаль — это диалоговое окно/всплывающее окно, которое отображается в верхней части текущей страницы:

Модальный заголовок

Модальный нижний колонтитул

Шаг 1) Добавить HTML:

Пример

class=»modal» is a container element for the modal and the div with class=»modal-content» is where you put your modal content (headings, paragraphs, images, etc).

The element with class=»close» should be used to close the modal.

Шаг 2) Добавить CSS:

Пример

/* Модальный (фон) */
.modal display: none; /* Скрыто по умолчанию */
position: fixed; /* Оставаться на месте */
z-index: 1; /* Сидеть на вершине */
left: 0;
top: 0;
width: 100%; /* Полная ширина */
height: 100%; /* Полная высота */
overflow: auto; /* Включите прокрутку, если это необходимо */
background-color: rgb(0,0,0); /* Цвет запасной вариант */
background-color: rgba(0,0,0,0.4); /* Черный с непрозрачностью */
>

/* Модальное содержание/коробка */
.modal-content background-color: #fefefe;
margin: 15% auto; /* 15% сверху и по центру */
padding: 20px;
border: 1px solid #888;
width: 80%; /* Может быть больше или меньше, в зависимости от размера экрана */
>

/* Кнопка закрытия */
.close color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
>

.close:hover,
.close:focus color: black;
text-decoration: none;
cursor: pointer;
>

The .modal class represents the window BEHIND the actual modal box. The height and width is set to 100%, which should create the illusion of a background window.

Добавить a black background color with opacity.

Set position to fixed; meaning it will move up and down the page when the user scrolls.

It is hidden by default, and should be shown with a click of a button (we’ll cover this later).

The .modal-content class

This is the actual modal box that gets focus. Do whatever you want with it. We have got you started with a border, some padding, and a background color. The margin: 15% auto is used to push the modal box down from the top (15%) and centering it (auto).

We also set the width to 400px — this could be more or less, depending on screen size. We will cover this later.

The .close class

The close button is styled with a large font-size, a specific color and floats to the right. We have also added some styles that will change the color of the close button when the user moves the mouse over it.

Шаг 3) Добавить JavaScript:

Пример

// Получить модальный
var modal = document.getElementById(«myModal»);

Читайте также:  Java parameters variable length

// Получить кнопку, которая открывает модальный
var btn = document.getElementById(«myBtn»);

// Получить элемент , который закрывает модальный
var span = document.getElementsByClassName(«close»)[0];

// Когда пользователь нажимает на кнопку, откройте модальный
btn.onclick = function() modal.style.display = «block»;
>

// Когда пользователь нажимает на (x), закройте модальное окно
span.onclick = function() modal.style.display = «none»;
>

// Когда пользователь щелкает в любом месте за пределами модального, закройте его
window.onclick = function(event) if (event.target == modal) modal.style.display = «none»;
>
>

Добавить верхний и нижний колонтитулы

Добавить класс для модального заголовка, модального тела и модального нижнего колонтитула:

Пример

×

Модальный заголовок

Некоторый текст в модальном теле

Какой-то другой текст.

Модальный нижний колонтитул

Стиль модального заголовка, тела и нижнего колонтитула, а также добавить анимацию (слайд в модели):

Пример

/* Модальный заголовок */
.modal-header padding: 2px 16px;
background-color: #5cb85c;
color: white;
>

/* Модальное тело */
.modal-body

/* Модальный нижний колонтитул */
.modal-footer padding: 2px 16px;
background-color: #5cb85c;
color: white;
>

/* Модальное содержание */
.modal-content position: relative;
background-color: #fefefe;
margin: auto;
padding: 0;
border: 1px solid #888;
width: 80%;
box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2),0 6px 20px 0 rgba(0,0,0,0.19);
animation-name: animatetop;
animation-duration: 0.4s
>

Нижний модальный («нижние листы»)

Пример того, как создать модальный режим полной ширины, который скользит снизу:

Пример

Совет:Кроме того, проверить Модальные изображения и Лайтбокс.

Источник

Всплывающее окно на HTML и CSS

Для вывода важных сообщений или просто изменений, произведённых на сайте, можно использовать всплывающие окна. Всплывающие окна бывают двух видов: обычные и модальные.

Примечание: модальные окна отличаются от обычных тем, что пока модальное окно открыто пользователь не может взаимодействовать с другими элементами сайта до тех пор, пока не закроет модальное окно.

Посмотреть пример модального окна можно с помощью JavaScript, воспользовавшись методом alert().

Всплывающее окно

Первым шагом создания всплывающего окна является создание элемента (или любого другого элемента) и его оформление:

     .okno  
Всплывающее окошко!

Этот и будет использоваться в качестве всплывающего окна. Теперь мы его скрываем с помощью значения none свойства display и добавляем ссылку, при нажатии на которую будет появляться всплывающее окно:

     #okno < width: 300px; height: 50px; text-align: center; padding: 15px; border: 3px solid #0000cc; border-radius: 10px; color: #0000cc; display: none; >#okno:target  
Всплывающее окошко!
Вызвать всплывающее окно

Используя псевдо-класс :target мы выбираем и применяем стили к элементу, к которому был осуществлён переход. Таким образом после перехода по ссылки значение свойства display элемента сменится с none на block .

Теперь надо расположить посередине страницы, чтобы он стал похож на всплывающее окно. Делаем его абсолютно позиционированным и центрируем его по вертикали и горизонтали:

Следующим шагом будет реализация скрытия окна, при нажатии на любое место страницы или на само окно. Для этого нам нужно расположить элемент внутри элемента :

     #main < display: none; position: absolute; top: 0; left: 0; width: 100%; height: 100%; >#okno < width: 300px; height: 50px; text-align: center; padding: 15px; border: 3px solid #0000cc; border-radius: 10px; color: #0000cc; position: absolute; top: 0; right: 0; bottom: 0; left: 0; margin: auto; >#main:target   
Всплывающее окошко!
Вызвать всплывающее окно

На этом создание простого всплывающего окна закончено.

Читайте также:  Python tkinter ввод чисел

Модальное окно

Для создания всплывающего модального окна, берём элемент , оформляем его и добавляем ссылку, при нажатии на которую он будет появляться:

     #okno < width: 300px; height: 50px; text-align: center; padding: 15px; border: 3px solid #0000cc; border-radius: 10px; color: #0000cc; display: none; position: absolute; top: 0; right: 0; bottom: 0; left: 0; margin: auto; >#okno:target  
Всплывающее окошко!
Вызвать всплывающее окно

Следующим шагом в создании полноценного модального окна будет добавление кнопки, которая будет скрывать наше окно. Кнопку сделаем из обычной ссылки, добавив её к нашему и оформив:

     #okno < width: 300px; height: 50px; text-align: center; padding: 15px; border: 3px solid #0000cc; border-radius: 10px; color: #0000cc; display: none; position: absolute; top: 0; right: 0; bottom: 0; left: 0; margin: auto; >#okno:target .close < display: inline-block; border: 1px solid #0000cc; color: #0000cc; padding: 0 12px; margin: 10px; text-decoration: none; background: #f2f2f2; font-size: 14pt; cursor:pointer; >.close:hover  
Всплывающее окошко!
Закрыть окно
Вызвать всплывающее окно

Для эффекта затемнения страницы при выводе модального окна, надо поместить весь имеющийся код окна в дополнительный :

Позиционируем родительский и растягиваем его на всю ширину и высоту окна. Задаём ему display: none; и перенаправляем ссылку вызова окна на него.

У дочернего убираем display: none; (он больше не нужен, так как родительский будет скрывать всё, что находится внутри него). В итоге родительский теперь отвечает за отображение модального окна и за затемнение фона страницы, а дочерний только за оформление самого окна:

     #zatemnenie < background: rgba(102, 102, 102, 0.5); width: 100%; height: 100%; position: absolute; top: 0; left: 0; display: none; >#okno < width: 300px; height: 50px; text-align: center; padding: 15px; border: 3px solid #0000cc; border-radius: 10px; color: #0000cc; position: absolute; top: 0; right: 0; bottom: 0; left: 0; margin: auto; background: #fff; >#zatemnenie:target .close < display: inline-block; border: 1px solid #0000cc; color: #0000cc; padding: 0 12px; margin: 10px; text-decoration: none; background: #f2f2f2; font-size: 14pt; cursor:pointer; >.close:hover  
Всплывающее окошко!
Закрыть окно
Вызвать всплывающее окно

Копирование материалов с данного сайта возможно только с разрешения администрации сайта
и при указании прямой активной ссылки на источник.
2011 – 2023 © puzzleweb.ru

Источник

How TO — CSS/JS Modal

Learn how to create a Modal Box with CSS and JavaScript.

How To Create a Modal Box

A modal is a dialog box/popup window that is displayed on top of the current page:

Step 1) Add HTML:

Example

class=»modal» is a container element for the modal and the div with class=»modal-content» is where you put your modal content (headings, paragraphs, images, etc).

The element with class=»close» should be used to close the modal.

Step 2) Add CSS:

Example

/* The Modal (background) */
.modal display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
>

Читайте также:  Программы java для нокиа

/* Modal Content/Box */
.modal-content background-color: #fefefe;
margin: 15% auto; /* 15% from the top and centered */
padding: 20px;
border: 1px solid #888;
width: 80%; /* Could be more or less, depending on screen size */
>

/* The Close Button */
.close color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
>

.close:hover,
.close:focus color: black;
text-decoration: none;
cursor: pointer;
>

The .modal class represents the window BEHIND the actual modal box. The height and width is set to 100%, which should create the illusion of a background window.

Add a black background color with opacity.

Set position to fixed; meaning it will move up and down the page when the user scrolls.

It is hidden by default, and should be shown with a click of a button (we’ll cover this later).

The .modal-content class

This is the actual modal box that gets focus. Do whatever you want with it. We have got you started with a border, some padding, and a background color. The margin: 15% auto is used to push the modal box down from the top (15%) and centering it (auto).

We also set the width to 400px — this could be more or less, depending on screen size. We will cover this later.

The .close class

The close button is styled with a large font-size, a specific color and floats to the right. We have also added some styles that will change the color of the close button when the user moves the mouse over it.

Step 3) Add JavaScript:

Example

// Get the modal
var modal = document.getElementById(«myModal»);

// Get the button that opens the modal
var btn = document.getElementById(«myBtn»);

// Get the element that closes the modal
var span = document.getElementsByClassName(«close»)[0];

// When the user clicks on the button, open the modal
btn.onclick = function() modal.style.display = «block»;
>

// When the user clicks on (x), close the modal
span.onclick = function() modal.style.display = «none»;
>

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) if (event.target == modal) modal.style.display = «none»;
>
>

Add a class for modal-header, modal-body and modal-footer:

Example

Some text in the Modal Body

Some other text.

Style the modal header, body and footer, and add animation (slide in the modal):

Example

/* Modal Header */
.modal-header padding: 2px 16px;
background-color: #5cb85c;
color: white;
>

/* Modal Footer */
.modal-footer padding: 2px 16px;
background-color: #5cb85c;
color: white;
>

/* Modal Content */
.modal-content position: relative;
background-color: #fefefe;
margin: auto;
padding: 0;
border: 1px solid #888;
width: 80%;
box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2),0 6px 20px 0 rgba(0,0,0,0.19);
animation-name: animatetop;
animation-duration: 0.4s
>

Bottom Modal («Bottom sheets»)

An example on how to create a full-width modal that slides in from the bottom:

Example

Tip: Also check out Modal Images and Lightbox.

Источник

Оцените статью