Modal

Эффект затухания

Теперь давайте применим ещё одну фишку, а именно, эффект затухания. Для этого div-у модального окна припишем класс fade:

<div id="modal" class="modal hide fade">
	<div class="modal-header">
		<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
		<h2>Lorem Ipsum</h2>
	</div>
	<div class="modal-body">
		<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.
		Donec placerat sem ipsum, ut faucibus nulla. Nullam mattis volutpat
		dolor, eu porta magna facilisis ut. In ultricies, purus sed pellentesque
		mollis, nibh tortor semper elit, eget rutrum purus nulla id quam.</p>
	</div>
</div>

Теперь открытие и закрытие нашего модального окна будет сопровождаться приятной для глаз анимацией. Данный эффект реализован в большей степень через CSS3.

Дизайн: Модальное окно

В Bootstrap класс modal-content содержит div-блоки modal-header, modal-body и modal-footer . Это структура модального окна.

<div class="modal fade" tabindex="-1" role="dialog">
  <div class="modal-dialog" role="document">
    <div class="modal-content">

      <div class="modal-header">
        <!-- Заголовок модального окна -->
      </div>

      <div class="modal-body">
        <!-- Тело модального окна -->
      </div>

      <div class="modal-footer">
        <!-- Футер модального окна -->
      </div>

    </div><!-- /.modal-content -->
  </div><!-- /.modal-dialog -->
</div><!-- /.modal -->

Этот код будет размещаться чуть выше JavaScript, как показано в структуре страницы. Смотрите пример, приведенный ниже.

5 последних уроков рубрики «Разное»

  • Выбрать хороший хостинг для своего сайта достаточно сложная задача. Особенно сейчас, когда на рынке услуг хостинга действует несколько сотен игроков с очень привлекательными предложениями. Хорошим вариантом является лидер рейтинга Хостинг Ниндзя — Макхост.

  • Как разместить свой сайт на хостинге? Правильно выбранный хороший хостинг — это будущее Ваших сайтов

    Проект готов, Все проверено на локальном сервере OpenServer и можно переносить сайт на хостинг. Вот только какую компанию выбрать? Предлагаю рассмотреть хостинг fornex.com. Отличное место для твоего проекта с перспективами бурного роста.

  • Создание вебсайта — процесс трудоёмкий, требующий слаженного взаимодействия между заказчиком и исполнителем, а также между всеми членами коллектива, вовлечёнными в проект. И в этом очень хорошее подспорье окажет онлайн платформа Wrike.

  • Подборка из нескольких десятков ресурсов для создания мокапов и прототипов.

Usage

The modal plugin toggles your hidden content on demand, via data attributes or JavaScript. It also adds to the to override default scrolling behavior and generates a to provide a click area for dismissing shown modals when clicking outside the modal.

Via data attributes

Activate a modal without writing JavaScript. Set on a controller element, like a button, along with a or to target a specific modal to toggle.

Options

Options can be passed via data attributes or JavaScript. For data attributes, append the option name to , as in .

Name Type Default Description
backdrop boolean or the string true Includes a modal-backdrop element. Alternatively, specify for a backdrop which doesn’t close the modal on click.
keyboard boolean true Closes the modal when escape key is pressed
focus boolean true Puts the focus on the modal when initialized.
show boolean true Shows the modal when initialized.

Methods

Activates your content as a modal. Accepts an optional options .

Manually toggles a modal. Returns to the caller before the modal has actually been shown or hidden (i.e. before the or event occurs).

Manually opens a modal. Returns to the caller before the modal has actually been shown (i.e. before the event occurs).

Manually hides a modal. Returns to the caller before the modal has actually been hidden (i.e. before the event occurs).

Events

Bootstrap’s modal class exposes a few events for hooking into modal functionality. All modal events are fired at the modal itself (i.e. at the ).

Event Type Description
show.bs.modal This event fires immediately when the instance method is called. If caused by a click, the clicked element is available as the property of the event.
shown.bs.modal This event is fired when the modal has been made visible to the user (will wait for CSS transitions to complete). If caused by a click, the clicked element is available as the property of the event.
hide.bs.modal This event is fired immediately when the instance method has been called.
hidden.bs.modal This event is fired when the modal has finished being hidden from the user (will wait for CSS transitions to complete).

Activating Bootstrap Modals with jQuery

The modal is a jQuery plugin, so if you want to control the modal using jQuery, you need to call the function on the modal’s selector. For Example:

The “options” here would be a JavaScript object that can be passed to customize the behavior. For example:

Available options include:

  • backdrop: This can be either or . This defines whether or not you want the user to be able to close the modal by clicking the background.
  • keyboard: if set to the modal will close via the ESC key.
  • show: used for opening and closing the modal. It can be either or .
  • focus: puts the focus on the modal when initialized. It can be either true or false and is set to by default.

How it works

Before getting started with Bootstrap’s modal component, be sure to read the following as our menu options have recently changed.

  • Modals are built with HTML, CSS, and JavaScript. They’re positioned over everything else in the document and remove scroll from the so that modal content scrolls instead.
  • Clicking on the modal “backdrop” will automatically close the modal.
  • Bootstrap only supports one modal window at a time. Nested modals aren’t supported as we believe them to be poor user experiences.
  • Modals use , which can sometimes be a bit particular about its rendering. Whenever possible, place your modal HTML in a top-level position to avoid potential interference from other elements. You’ll likely run into issues when nesting a within another fixed element.
  • One again, due to , there are some caveats with using modals on mobile devices. for details.
  • Lastly, the HTML attribute has no affect in modals. Here’s how you can achieve the same effect with custom JavaScript.

Keep reading for demos and usage guidelines.

Due to how HTML5 defines its semantics, the autofocus HTML attribute has no effect in Bootstrap modals. To achieve the same effect, use some custom JavaScript:

Полная структура страницы

Это полная структура страницы, которая требуется для создания модальных окон. Создайте страницу Index.html и добавьте в нее приведенный ниже код.

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
 
    
    <div class="modal fade" tabindex="-1" role="dialog">
      <div class="modal-dialog" role="document">
        <div class="modal-content">

        <div class="modal-header">
          <!-- Заголовок модального окна -->
        </div>

        <div class="modal-body">
          <!-- Тело модального окна -->
        </div>

        <div class="modal-footer">
          <!-- Футер модального окна -->
        </div>

        </div><!-- /.modal-content -->
      </div><!-- /.modal-dialog -->
    </div><!-- /.modal -->
 
      
    <!-- Здесь помещаются JS файлы. -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

</body>
</html>

Теперь создадим модальные формы входа, регистрации и восстановления пароля. Единственное модальное окно, которое я использовал в примере, с тремя <div class=»modal-content»>. По умолчанию оно будет формой входа в систему. Такие же блоки мы создаем для других функций, все они будут иметь разные идентификаторы. Смотрите пример, приведенный ниже.

<div class="modal fade" tabindex="-1" role="dialog">
  <div class="modal-dialog" role="document">

    <div class="modal-content" id="login-modal-content">

      <div class="modal-header">
        <!-- Заголовок Login -->
      </div>
      <div class="modal-body">
        <!-- Тело Login -->
      </div>
      <div class="modal-footer">
        <!-- Футер Login -->
      </div>

    </div>

    <div class="modal-content" id="signup-modal-content">

      <div class="modal-header">
        <!-- Заголовок Signup -->
      </div>
      <div class="modal-body">
        <!-- Тело Signup -->
      </div>
      <div class="modal-footer">
        <!-- Футер Signup -->
      </div>

    </div>

    <div class="modal-content" id="forgot-password-modal-content">

      <div class="modal-header">
        <!-- Заголовок Forgot Password -->
      </div>
      <div class="modal-body">
        <!-- Тело Forgot Password -->
      </div>
      <div class="modal-footer">
        <!-- Футер Forgot Password -->
      </div>

Содержимое модального окна для авторизации будет использоваться по умолчанию. Остальные два блока скрыты и их можно будет отобразить при нажатии на конкретные ссылки, указанные во всех футерах.

Optional Sizes#

You can specify a bootstrap large or small modal by using the «size» prop.

Small modal Large modal

function Example() {
const = useState(false);
const = useState(false);

return (
<>
<Button onClick={() => setSmShow(true)}>Small modal</Button>{‘ ‘}
<Button onClick={() => setLgShow(true)}>Large modal</Button>
<Modal
size=»sm»
show={smShow}
onHide={() => setSmShow(false)}
aria-labelledby=»example-modal-sizes-title-sm»
>
<Modal.Header closeButton>
<Modal.Title id=»example-modal-sizes-title-sm»>
Small Modal
</Modal.Title>
</Modal.Header>
<Modal.Body>…</Modal.Body>
</Modal>
<Modal
size=»lg»
show={lgShow}
onHide={() => setLgShow(false)}
aria-labelledby=»example-modal-sizes-title-lg»
>
<Modal.Header closeButton>
<Modal.Title id=»example-modal-sizes-title-lg»>
Large Modal
</Modal.Title>
</Modal.Header>
<Modal.Body>…</Modal.Body>
</Modal>
</>
);
}

render(<Example />);

functionExample(){

constsmShow, setSmShow=useState(false);

constlgShow, setLgShow=useState(false);

return(

<>

<ButtononClick={()=>setSmShow(true)}>Small modal</Button>{' '}

<ButtononClick={()=>setLgShow(true)}>Large modal</Button>

<Modal

size="sm"

show={smShow}

onHide={()=>setSmShow(false)}

aria-labelledby="example-modal-sizes-title-sm"

>

<Modal.HeadercloseButton>

<Modal.Titleid="example-modal-sizes-title-sm">
            Small Modal
</Modal.Title>

</Modal.Header>

<Modal.Body>...</Modal.Body>

</Modal>

<Modal

size="lg"

show={lgShow}

onHide={()=>setLgShow(false)}

aria-labelledby="example-modal-sizes-title-lg"

>

<Modal.HeadercloseButton>

<Modal.Titleid="example-modal-sizes-title-lg">
            Large Modal
</Modal.Title>

</Modal.Header>

<Modal.Body>...</Modal.Body>

</Modal>

</>

);

}

render(<Example/>);

Sizing modals using custom CSS

You can apply custom css to the modal dialog div using the «dialogClassName» prop. Example is using a custom css class with width set to 90%.

Custom Width Modal

function Example() {
const = useState(false);

return (
<>
<Button variant=»primary» onClick={() => setShow(true)}>
Custom Width Modal
</Button>

<Modal
show={show}
onHide={() => setShow(false)}
dialogClassName=»modal-90w»
aria-labelledby=»example-custom-modal-styling-title»
>
<Modal.Header closeButton>
<Modal.Title id=»example-custom-modal-styling-title»>
Custom Modal Styling
</Modal.Title>
</Modal.Header>
<Modal.Body>
<p>
Ipsum molestiae natus adipisci modi eligendi? Debitis amet quae unde
commodi aspernatur enim, consectetur. Cumque deleniti temporibus
ipsam atque a dolores quisquam quisquam adipisci possimus
laboriosam. Quibusdam facilis doloribus debitis! Sit quasi quod
accusamus eos quod. Ab quos consequuntur eaque quo rem! Mollitia
reiciendis porro quo magni incidunt dolore amet atque facilis ipsum
deleniti rem!
</p>
</Modal.Body>
</Modal>
</>
);
}

render(<Example />);

functionExample(){

constshow, setShow=useState(false);

return(

<>

<Buttonvariant="primary"onClick={()=>setShow(true)}>
        Custom Width Modal
</Button>

<Modal

show={show}

onHide={()=>setShow(false)}

dialogClassName="modal-90w"

aria-labelledby="example-custom-modal-styling-title"

>

<Modal.HeadercloseButton>

<Modal.Titleid="example-custom-modal-styling-title">
            Custom Modal Styling
</Modal.Title>

</Modal.Header>

<Modal.Body>

<p>

            Ipsum molestiae natus adipisci modi eligendi? Debitis amet quae unde

            commodi aspernatur enim, consectetur. Cumque deleniti temporibus
            ipsam atque a dolores quisquam quisquam adipisci possimus
            laboriosam. Quibusdam facilis doloribus debitis! Sit quasi quod

            accusamus eos quod. Ab quos consequuntur eaque quo rem! Mollitia
            reiciendis porro quo magni incidunt dolore amet atque facilis ipsum
            deleniti rem!

</p>

</Modal.Body>

</Modal>

</>

);

}

render(<Example/>);

JQuery часть

Рассмотрим код jQuery. В нем используются методы FadeOut и FadeIn, которые срабатывают при клике по ссылкам футера. После чего формы меняются местами.

<script>
$(document).ready(function(){
      
    $('#Login-Form').parsley();
    $('#Signin-Form').parsley();
    $('#Forgot-Password-Form').parsley();
     
    $('#signupModal').click(function(){         
     $('#login-modal-content').fadeOut('fast', function(){
        $('#signup-modal-content').fadeIn('fast');
     });
    });
           
    $('#loginModal').click(function(){          
     $('#signup-modal-content').fadeOut('fast', function(){
        $('#login-modal-content').fadeIn('fast');
     });
    });
      
    $('#FPModal').click(function(){         
     $('#login-modal-content').fadeOut('fast', function(){
        $('#forgot-password-modal-content').fadeIn('fast');
        });
    });
      
    $('#loginModal1').click(function(){          
     $('#forgot-password-modal-content').fadeOut('fast', function(){
        $('#login-modal-content').fadeIn('fast');
     });
    });
        
});
</script>

Events

Bootstrap’s modal class includes few events for hooking into modal functionality.

Event Description
show.bs.modal This event fires immediately when the show instance method is called.
shown.bs.modal This event is fired when the modal has been made visible to the user. It will wait until the CSS transition process has been fully completed before getting fired.
hide.bs.modal This event is fired immediately when the hide instance method has been called.
hidden.bs.modal This event is fired when the modal has finished being hidden from the user. It will wait until the CSS transition process has been fully completed before getting fired.

The following example displays an alert message to the user when fade out transition of the modal window has been fully completed.

Example

Try this code

Tip: See also the section for more examples on modals, like setting vertical alignment, changing default width, embedding video, etc.

The Default Modal

The default Bootstrap Modal looks like this:

To trigger the modal, you’ll need to include a link or a button. The markup for the trigger element might look like this:

Notice the link element has two custom data attributes: and . The toggle tells Bootstrap what to do and the target tells Bootstrap which element is going to open. So whenever a link like that is clicked, a modal with an ID of “basicModal” will appear.

Now let’s see the code required to define the modal itself. Here’s the markup:

The parent of the modal should have the same ID as used in the trigger element above. In our case, it would be .

Note: Custom attributes like and in the parent modal element are used for accessibility. It’s good practice to make your website accessible to all, so you should include these attributes since they won’t negatively affect the standard functionality of the modal.

In the modal’s HTML, we can see a wrapper nested inside the parent modal . This has a class of that tells where to look for the contents of the modal. Inside this , we need to place the three sections I mentioned earlier: the header, body, and footer.

The modal header, as the name implies, is used to give the modal a title and some other elements like the “x” close button. This should have a attribute that tells Bootstrap to remove the element.

Then we have the modal body, a sibling of the modal header. Consider the body an open canvas to play with. You can add any kind of data inside the body, including a YouTube video embed, an image, or just about anything else.

Lastly, we have the modal footer. This area is by default right aligned. In this area you could place action buttons like “Save”, “Close”, “Accept”, etc., that are associated with the action the modal is displaying.

Now we’re done with our first modal! You can check it out on our demo page.

Большое и маленькое модальное окно

<p>
    <button class="btn btn-primary" data-toggle="modal" data-target="#modal-example-lg">
        Большое окно
    </button>
    <button class="btn btn-primary" data-toggle="modal" data-target="#modal-example-sm">
        Маленькое окно
    </button>
</p>
<!-- Большое окно -->
<div class="modal fade" id="modal-example-lg" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">Заголовок окна</h4>
                <button type="button" class="close" data-dismiss="modal" aria-label="Закрыть">
                    <span aria-hidden="true">&times;</span>
                </button>

            </div>
            <div class="modal-body">
                <p>
                    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
                    eiusmodtempor incididunt ut labore et dolore magna aliqua. Ut enim
                    ad minim veniam, quis nostrud exercitation ullamco laboris nisi
                    ut aliquip ex ea commodo consequat.
                </p>
                <p>
                    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
                    eiusmodtempor incididunt ut labore et dolore magna aliqua. Ut enim
                    ad minim veniam, quis nostrud exercitation ullamco laboris nisi
                    ut aliquip ex ea commodo consequat.
                </p>
            </div>
        </div>
    </div>
</div>
<!-- Маленькое окно -->
<div class="modal fade" id="modal-example-sm" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-sm" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">Заголовок окна</h4>
                <button type="button" class="close" data-dismiss="modal" aria-label="Закрыть">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
                eiusmodtempor incididunt ut labore et dolore magna aliqua.
            </div>
        </div>
    </div>
</div>

Options

There are certain options which can be passed to Bootstrap method to customize the functionality of a modal. Options can be passed via data attributes or JavaScript.

For setting the modals options via data attributes, just append the option name to , such as , , and so on.

Name Type Default Value Description
backdrop boolean or the string true Includes a modal-backdrop (black overlay area) element. Alternatively, you may specify for a backdrop which doesn’t close the modal on click.
keyboard boolean true Closes the modal window on press of escape key.
focus boolean true Puts the focus on the modal when initialized.
show boolean true Shows the modal when initialized or activate.

Data attributes provides an easy way for setting the modal options, however JavaScript is the more preferable way as it prevents you from repetitive work. See the method in the section below to know how to set the options for modals using JavaScript.

In the following example we’ve set the option to (line no-5) which prevents the modal from closing when clicking outside of the modal i.e. the black overlay area.

Explanation of Code

To activate a Bootstrap modal via data attributes we basically need two components — the controller element like a button or link, and the modal element itself.

  • The outermost container of every modal in a document must have a unique id (in this case , line no-5), so that it can be targeted via (for buttons) or (for hyperlinks) attribute of the controller element (line no-2).
  • The attribute is required to add on the controller element (line no-2), like a button or an anchor, along with a attribute or to target a specific modal to toggle.
  • The class (line no-6) sets the width as well as horizontal and vertical alignment of the modal box. Whereas the class sets the styles like text and background color, borders, rounded corners etc.

Rest of the thing is self explanatory, such as the element defines a header for the modal that usually contains a modal title and a close button, whereas the element contains the actual content like text, images, forms etc. and the element defines the footer that typically contains action buttons for the user.

Note: The class on the element adds a fading and sliding animation effect while showing and hiding the modal window. If you want the modal that simply appear without any effect you can just remove this class. Also, when modals become too long for the user’s viewport or device, they scroll independent of the page itself.

Creating Modals with Bootstrap

Modal is basically a dialog box or popup window that is used to provide important information to the user or prompt user to take necessary actions before moving on. Modals are widely used to warn users for situations like session time out or to receive their final confirmation before going to perform any critical actions such as saving or deleting important data.

You can easily create very smart and flexible dialog boxes with the Bootstrap modal plugin. The following example oulines the basic structure to create a simple modal with a header, message body and the footer containing action buttons for the user.

Example

Try this code

— If you try out the above example, it will launches the modal window automatically when the DOM is fully loaded via JavaScript. The output will look something like this:

Tip: Always try to place your modal HTML in a top-level position in your document, preferably before closing of the tag (i.e. ) to avoid interference from other elements, otherwise it may affect modal’s appearance or functionality.

Check out the snippets section for examples of some beautifully designed Bootstrap modals.

Дизайн: Структура страницы

Ниже приведен код HTML страницы, в которой подключаются необходимые файлы CSS и JS:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
 
<!-- Здесь будет модальное окно ... --> 
 
<!-- Здесь помещаются JS файлы. -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

</body>
</html>

Параметры модального окна

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

Параметр Описание
Значение по умолчанию: . Накладывает темный фон над всем содержимым веб-страницы, поверх которого отображается модальное окно. У данного параметра есть дополнительное значение , которое запрещает закрывать модальное окно при клике за его пределами. Параметр также можно установить с помощью атрибута data-backdrop.
Значение по умолчанию: . Закрывает модальное окно при нажатии клавиши . Данный параметр также можно установить с помощью атрибута .
Значение по умолчанию: . Отображает модальное окно сразу после его инициализации. Данный параметр также можно установить с помощью атрибута .
Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Adblock
detector