Dialog box in html

Dialog box in html

Тег (от англ. dialog — диалог) задает диалоговое окно, в котором можно выводить сообщение или форму, например, для входа на сайт.

Диалоговое окно отображается со следующим предустановленным стилем.

position: absolute; left: 0; right: 0; margin: auto; border: solid; padding: 1em; background: white; color: black; 

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

Для отображения и сокрытия диалогового окна применяются, соответственно, методы show() и hide() , как показано в примере ниже. Кроме того, диалог можно превратить в модальное окно, используя вместо show() метод showModal() . В этом случае остальные элементы на странице блокируются — текст нельзя выделить, а кнопки нажать до тех пор, пока диалоговое окно не будет закрыто. Также модальное окно можно закрыть клавишей Esc .

Поддержка браузерами¶

Can I Use dialog? Data on support for the dialog feature across the major browsers from caniuse.com.

Полифилы для включения поддержки:

Синтаксис¶

Закрывающий тег обязателен.

Атрибуты¶

open Отображает диалоговое окно. Без этого атрибута в стилях к нему добавляется display: none и окно не выводится в браузере.

Для этого элемента также доступны универсальные атрибуты.

Спецификации¶

Описание и примеры¶

Пример 1¶

 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
 html> head> meta charset="utf-8" /> title>dialogtitle> style> body  background: url(/example/image/shark.jpg) no-repeat; background-size: cover; > dialog  background: rgba(255, 255, 255, 0.7); width: 300px; box-shadow: 0 0 5px rgba(0, 0, 0, 0.5); border-radius: 5px; > style> head> body> button id="openDialog">Открыть окноbutton> dialog> p> Полинезийцы называют Млечный путь Манго-Роа-И-Ата, что в переводе с маори означает «Длинная акула на рассвете». p> p>button id="closeDialog">Закрыть окноbutton>p> dialog> script> var dialog = document.querySelector('dialog') document.querySelector( '#openDialog' ).onclick = function ()  dialog.show() // Показываем диалоговое окно > document.querySelector( '#closeDialog' ).onclick = function ()  dialog.close() // Прячем диалоговое окно > script> body> html> 

Пример 2¶

dialog open> p>Greetings, one and all!p> dialog> 

Пример 3¶

 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
 dialog id="favDialog"> form method="dialog"> section> p> label for="favAnimal">Favorite animal:label> select id="favAnimal"> option>option> option>Brine shrimpoption> option>Red pandaoption> option>Spider monkeyoption> select> p> section> menu> button id="cancel" type="reset">Cancelbutton> button type="submit">Confirmbutton> menu> form> dialog> menu> button id="updateDetails">Update detailsbutton> menu> script> ;(function ()  var updateButton = document.getElementById( 'updateDetails' ) var cancelButton = document.getElementById('cancel') var favDialog = document.getElementById('favDialog') // Update button opens a modal dialog updateButton.addEventListener('click', function ()  favDialog.showModal() >) // Form cancel button closes the dialog box cancelButton.addEventListener('click', function ()  favDialog.close() >) >)() script> 

Источник

: The Dialog element

The HTML element represents a dialog box or other interactive component, such as a dismissible alert, inspector, or subwindow.

Attributes

This element includes the global attributes.

Warning: The tabindex attribute must not be used on the element.

Indicates that the dialog is active and can be interacted with. When the open attribute is not set, the dialog shouldn’t be shown to the user. It is recommended to use the .show() or .showModal() methods to render dialogs, rather than the open attribute. If a is opened using the open attribute, it will be non-modal.

Accessibility considerations

The native HTML element should be used in creating modal dialogs as it provides usability and accessibility features that must be replicated if using other elements for a similar purpose. Use the appropriate .showModal() or .show() method to render dialogs. If creating a custom dialog implementation, ensure all expected default behaviors are supported and proper labeling recommendations are followed.

When implementing a dialog, it is important to consider the most appropriate place to set user focus. Explicitly indicating the initial focus placement by use of the autofocus attribute will help ensure initial focus is set to the element deemed the best initial focus placement for any particular dialog. When in doubt, as it may not always be known where initial focus could be set within a dialog, particularly for instances where a dialog’s content is dynamically rendered when invoked, then if necessary authors may decide focusing the element itself would provide the best initial focus placement. When using HTMLDialogElement.showModal() to open a , focus is set on the first nested focusable element.

Ensure a mechanism is provided to allow users to close a dialog. The most robust way to ensure all users can close a dialog is to include an explicit button to do so. For instance, a confirmation, cancel or close button as appropriate. Additionally, for those using a device with a keyboard, the Escape key is commonly expected to close modal dialogs as well. By default, a invoked by the showModal() method will allow for its dismissal by the Escape . A non-modal dialog does not dismiss via the Escape key by default, and depending on what the non-modal dialog represents, it may not be desired for this behavior. If multiple modal dialogs are open, Escape should only close the last shown dialog. When using , this behavior is provided by the browser.

The element is exposed by browsers similarly to custom dialogs using the ARIA role=»dialog» attribute. elements invoked by the showModal() method will have an implicit aria-modal=»true», whereas elements invoked by the show() method, or rendered by use of the open attribute or changing the default display of a will be exposed as [aria-modal=»false»] . When implementing modal dialogs, everything other than the and its contents should be rendered inert using the inert attribute. When using along with the HTMLDialogElement.showModal() method, this behavior is provided by the browser.

Usage notes

  • elements can close a if they have the attribute method=»dialog» or if the button used to submit the form has formmethod=»dialog» set. In this case, the state of the form controls are saved, not submitted, the closes, and the returnValue property gets set to the value of the button that was used to save the form’s state.
  • The ::backdrop CSS pseudo-element can be used to style the backdrop that is displayed behind a element when the dialog is displayed with HTMLDialogElement.showModal() . For example, to dim unreachable content behind the modal dialog.

Examples

Simple example

The following will render a non-modal, or modal-less, dialog. The «OK» button allows the dialog to be closed when activated.

dialog open> p>Greetings, one and all!p> form method="dialog"> button>OKbutton> form> dialog> 

Result

Because this dialog was opened via the open attribute, it is non-modal. In this example, when the dialog is dismissed, no method is provided to re-open it. Opening dialogs via HTMLDialogElement.show() is preferred over the toggling of the boolean open attribute.

Advanced example

This example opens a modal dialog when the «Show the dialog» button is activated. The dialog contains a form with a and two elements which default to type=»submit» . Updating the value of the updates the value of the «confirm» button. This value is the returnValue . If the dialog is closed with the Esc key, there is no return value. When the dialog is closed, the return value is displayed under the «Show the dialog» button.

HTML

dialog id="favDialog"> form> p> label> Favorite animal: select> option value="default">Choose…option> option>Brine shrimpoption> option>Red pandaoption> option>Spider monkeyoption> select> label> p> div> button value="cancel" formmethod="dialog">Cancelbutton> button id="confirmBtn" value="default">Confirmbutton> div> form> dialog> p> button id="showDialog">Show the dialogbutton> p> output>output> 

JavaScript

const showButton = document.getElementById("showDialog"); const favDialog = document.getElementById("favDialog"); const outputBox = document.querySelector("output"); const selectEl = favDialog.querySelector("select"); const confirmBtn = favDialog.querySelector("#confirmBtn"); // "Show the dialog" button opens the modally showButton.addEventListener("click", () =>  favDialog.showModal(); >); // "Favorite animal" input sets the value of the submit button selectEl.addEventListener("change", (e) =>  confirmBtn.value = selectEl.value; >); // "Cancel" button closes the dialog without submitting because of [formmethod="dialog"], triggering a close event. favDialog.addEventListener("close", (e) =>  outputBox.value = favDialog.returnValue === "default" ? "No return value." : `ReturnValue: $favDialog.returnValue>.`; // Have to check for "default" rather than empty string >); // Prevent the "confirm" button from the default behavior of submitting the form, and close the dialog with the `close()` method, which triggers the "close" event. confirmBtn.addEventListener("click", (event) =>  event.preventDefault(); // We don't want to submit this fake form favDialog.close(selectEl.value); // Have to send the select box value here. >); 

Result

This modal dialog can be closed three ways. For keyboard users, modal dialogs can be closed with the Esc key. In this example, the «Cancel» button closes the dialog via the dialog form method and the «Confirm» closes the dialog via the HTMLDialogElement.close() method. The «Cancel» button includes a formmethod=»dialog» , which overrides the ‘s default GET method . When a form’s method is dialog , the state of the form is saved, not submitted, and the dialog gets closed. Without an action , submitting the form via the default GET method causes a page to reload. We use JavaScript to prevent the submission and close the dialog with the event.preventDefault() and HTMLDialogElement.close() methods, respectively.

It is important to provide a closing mechanism within every dialog element. The Esc key does not close non-modal dialogs by default, nor can one assume that a user will even have access to a physical keyboard (e.g., someone using a touch screen device without access to a keyboard).

Technical summary

Content categories Flow content, sectioning root
Permitted content Flow content
Tag omission None, both the starting and ending tag are mandatory.
Permitted parents Any element that accepts flow content
Implicit ARIA role dialog
Permitted ARIA roles alertdialog
DOM interface HTMLDialogElement

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Источник

Читайте также:  Python minidom create xml
Оцените статью