Open and close
- Dialogs need a mask and a window to display information, so there should be at least two levels of structure.
<div class="dialog">
<div class="dialog__body">
<div>blalala</div>
</div>
</div>
Copy the code
.dialog is used to make the mask.
.dialog{// Create a translucent black mask that fills the entire user interfaceposition: fixed;
left: 0;
top: 0;
width: 100vw;
height: 100vh;
background-color: # 333333ee;
}
Copy the code
.dialog__body is the window that displays the information
.dialog__body {
background: white; // Center the window displaying the information horizontallywidth: 80%;
margin-left: 10%; // Distance to the top100pxCan be adjusted,height: 500px;
margin-top: 100px;
}
Copy the code
- Next, add buttons that control open and close
<button class="trigger">Open the dialog box</button>
<div class="dialog">
<div class="dialog__body">
<div>blalala</div>
<button class="dialog__close">Close dialog</button>
</div>
</div>
Copy the code
By default, no dialog box is displayed
.dialog {
display: none; / /... Ditto}Copy the code
Add a class to control the display of the dialog box
.dialog--active {
display: block;
}
Copy the code
Add.dialog–active to.dialog when open, remove.dialog–active when closed.
// Open the dialog box
var trigger = document.querySelector('.trigger');
trigger.addEventListener('click'.function() {
var dialog = document.querySelector('.dialog');
if(! dialog.classList.contains('dialog--active')) {
dialog.classList.add('dialog--active')}})// Close the dialog box
var closeBtn = document.querySelector('.dialog__close')
closeBtn.addEventListener('click'.function () {
var dialog = document.querySelector('.dialog');
if (dialog.classList.contains('dialog--active')) {
dialog.classList.remove('dialog--active')}})Copy the code
- Finally, add a little animation to make the interaction a little softer
@keyframes pop {
0% {
opacity: 0;
}
100% {
opacity: 1; }}.dialog{/ /... Same as aboveanimation: pop 0.3 s;
}
Copy the code
Online code demo jsbin.com/ditatevegu/…
Prevents the page from continuing to scroll when the dialog box opens
Usually we use dialogs to prevent the user from using the page until the dialog is complete.
So, if the page is very long and has a scrollbar, we need to hide the scrollbar, as follows:
- Find the scroll element
- When the dialog opens, set the overflow property of the scrolling element to hidden
- When you close the dialog box, set the overflow property of the scrolling element to the default
// ...
if(! dialog.classList.contains('dialog--active')) {
// ...
document.scrollingElement.style.overflow = 'hidden';
}
// ...
if (dialog.classList.contains('dialog--active')) {
// ...
document.scrollingElement.style.overflow = 'revert';
}
Copy the code
Online code demo jsbin.com/zefunuw/edi…