Javascript открыть во весь экран

Guide to the Fullscreen API

This article demonstrates how to use the Fullscreen API to place a given element into fullscreen mode, as well as how to detect when the browser enters or exits fullscreen mode.

Activating fullscreen mode

Given an element that you’d like to present in fullscreen mode (such as a , for example), you can present it in fullscreen mode by calling its requestFullscreen() method.

video controls id="myvideo"> source src="somevideo.webm">source> source src="somevideo.mp4">source> video> 

We can put that video into fullscreen mode as follows:

const elem = document.getElementById("myvideo"); if (elem.requestFullscreen)  elem.requestFullscreen(); > 

This code checks for the existence of the requestFullscreen() method before calling it.

Presentation differences

It’s worth noting a key difference here between the Gecko and WebKit implementations at this time: Gecko automatically adds CSS rules to the element to stretch it to fill the screen: » width: 100%; height: 100% «. WebKit doesn’t do this; instead, it centers the fullscreen element at the same size in a screen that’s otherwise black. To get the same fullscreen behavior in WebKit, you need to add your own » width: 100%; height: 100%; » CSS rules to the element yourself:

#myvideo:-webkit-full-screen  width: 100%; height: 100%; > 

On the other hand, if you’re trying to emulate WebKit’s behavior on Gecko, you need to place the element you want to present inside another element, which you’ll make fullscreen instead, and use CSS rules to adjust the inner element to match the appearance you want.

Notification

When fullscreen mode is successfully engaged, the document which contains the element receives a fullscreenchange event. When fullscreen mode is exited, the document again receives a fullscreenchange event. Note that the fullscreenchange event doesn’t provide any information itself as to whether the document is entering or exiting fullscreen mode, but if the document has a non null fullscreenElement , you know you’re in fullscreen mode.

When a fullscreen request fails

It’s not guaranteed that you’ll be able to switch into fullscreen mode. For example, elements have the allowfullscreen attribute in order to opt-in to allowing their content to be displayed in fullscreen mode. In addition, certain kinds of content, such as windowed plug-ins, cannot be presented in fullscreen mode. Attempting to put an element which can’t be displayed in fullscreen mode (or the parent or descendant of such an element) won’t work. Instead, the element which requested fullscreen will receive a mozfullscreenerror event. When a fullscreen request fails, Firefox will log an error message to the Web Console explaining why the request failed. In Chrome and newer versions of Opera however, no such warning is generated.

Note: Fullscreen requests need to be called from within an event handler or otherwise they will be denied.

Getting out of full screen mode

The user always has the ability to exit fullscreen mode of their own accord; see Things your users want to know. You can also do so programmatically by calling the Document.exitFullscreen() method.

Other information

The Document provides some additional information that can be useful when developing fullscreen web applications:

The fullscreenElement property tells you the Element that’s currently being displayed fullscreen. If this is non-null, the document (or shadow DOM) is in fullscreen mode. If this is null, the document (or shadow DOM) is not in fullscreen mode.

The fullscreenEnabled property tells you whether or not the document is currently in a state that would allow fullscreen mode to be requested.

Viewport scaling in mobile browsers

Some mobile browsers while in fullscreen mode ignore viewport meta-tag settings and block user scaling; for example: a «pinch to zoom» gesture may not work on a page presented in fullscreen mode — even if, when not in fullscreen mode, the page can be scaled using pinch to zoom.

Things your users want to know

You’ll want to be sure to let your users know that they can press the Esc key (or F11 ) to exit fullscreen mode.

In addition, navigating to another page, changing tabs, or switching to another application (using, for example, Alt — Tab ) while in fullscreen mode exits fullscreen mode as well.

Example

In this example, a video is presented in a web page. Pressing the Return or Enter key lets the user toggle between windowed and fullscreen presentation of the video.

Watching for the Enter key

When the page is loaded, this code is run to set up an event listener to watch for the Enter key.

.addEventListener( "keydown", (e) =>  if (e.keyCode === 13)  toggleFullScreen(); > >, false, ); 

Toggling fullscreen mode

This code is called when the user hits the Enter key, as seen above.

function toggleFullScreen()  if (!document.fullscreenElement)  document.documentElement.requestFullscreen(); > else if (document.exitFullscreen)  document.exitFullscreen(); > > 

This starts by looking at the value of the fullscreenElement attribute on the document . If it’s null , the document is currently in windowed mode, so we need to switch to fullscreen mode. Switching to fullscreen mode is done by calling element.requestFullscreen() .

If fullscreen mode is already active ( fullscreenElement is non- null ), we call document.exitFullscreen() .

Prefixing

For the moment not all browsers are implementing the unprefixed version of the API (for vendor agnostic access to the Fullscreen API you can use Fscreen). Here is the table summarizing the prefixes and name differences between them:

Standard WebKit (Safari) / Blink (Chrome & Opera) / Edge Gecko (Firefox) Internet Explorer
Document.fullscreen Deprecated webkitIsFullScreen mozFullScreen
Document.fullscreenEnabled webkitFullscreenEnabled mozFullScreenEnabled msFullscreenEnabled
Document.fullscreenElement webkitFullscreenElement mozFullScreenElement msFullscreenElement
Document.exitFullscreen() webkitExitFullscreen() mozCancelFullScreen() msExitFullscreen()
Element.requestFullscreen() webkitRequestFullscreen() mozRequestFullScreen() msRequestFullscreen()

Specifications

Browser compatibility

api.Document.fullscreenEnabled

BCD tables only load in the browser

api.Document.fullscreen

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Jul 7, 2023 by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

Полноэкранный режим в JavaScript

Полноэкранный режим в JavaScript

Относительно недавно один из моих учеников спросил меня: как сделать так, чтобы при нажатии на кнопку элемент страницы (параграф, картинка и т.д.) стали бы отображаться на полный экран (Fullscreen).

К счастью для этого существует встроенный браузерный механизм под названием Fullscreen API.

Прикладной интерфейс Fullscreen API

Прикладной интерфейс Fullscreen API предоставляет два метода, два события и одно свойство.

  • Метод Element.requestFullscreen() переводит элемент страницы в полноэкранный режим.
  • Метод document.exitFullscreen() выходит из полноэкранного режима (всегда вызывается на объекте document).
  • Событие fullscreenchange возникает, когда элемент входит в полноэкранный режим или выходит из него
  • Событие fullscreenerror возникает, когда элемент не может быть переведен в полноэкранный режим
  • Свойство document.fullscreenElement сообщает какой из элементов находится в полноэкранном режиме на странице в данный момент

Пример

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

Для функционирования этой кнопки, в первую очередь необходимо создать слушатель для событий клика только по данной кнопке. Это делается следующим образом.

// игнорирование событий, которые произошли не на данной кнопке
if( !event.target.hasAttribute(‘data-toggle-fullscreen’) ) return;

Затем, нам необходимо использовать свойство document.fullscreenElement для того, чтобы проверить находится ли уже какой-либо элемент страницы в полноэкранном режиме или нет. Если да, то мы используем метод document.exitFullscreen() для выхода из полноэкранного режима. В противном случае, вызовем requestFullscreen() на объекте document.documentElement.

document.addEventListener(‘click’, function (event)

// игнорирование событий, которые произошли не на данной кнопке
if (!event.target.hasAttribute(‘data-toggle-fullscreen’)) return;

// если элемент уже в полноэкранном режиме, выйти из него
// В противном случае войти в полный экран
if (document.fullscreenElement) document.exitFullscreen();
> else document.documentElement.requestFullscreen();
>

Совместимость с браузерами

Fullscreen API работает во всех современных браузерах, в том числе в IE11 и выше. Однако, многие браузеры используют префиксные имплементации (как, mozRequestFullscreen) вместо стандартных.

Поэтому, чтобы данная функциональность работала во всех браузерах стандартным образом, нужно использовать полифилы для requestFullscreen(), exitFullscreen() и fullscreenElement, которые дают возможность использовать методы Fullscreen API без префиксов вендоров.

А, если вам необходимо использовать еще и события, то в этом случае я рекомендую вам полнофункциональный полифил Fullscreen API Polyfill. На этом все. Спасибо за внимание!

Создано 13.09.2018 10:20:44

  • Михаил Русаков
  • Копирование материалов разрешается только с указанием автора (Михаил Русаков) и индексируемой прямой ссылкой на сайт (http://myrusakov.ru)!

    Добавляйтесь ко мне в друзья ВКонтакте: http://vk.com/myrusakov.
    Если Вы хотите дать оценку мне и моей работе, то напишите её в моей группе: http://vk.com/rusakovmy.

    Если Вы не хотите пропустить новые материалы на сайте,
    то Вы можете подписаться на обновления: Подписаться на обновления

    Если у Вас остались какие-либо вопросы, либо у Вас есть желание высказаться по поводу этой статьи, то Вы можете оставить свой комментарий внизу страницы.

    Порекомендуйте эту статью друзьям:

    Если Вам понравился сайт, то разместите ссылку на него (у себя на сайте, на форуме, в контакте):

    1. Кнопка:
      Она выглядит вот так:
    2. Текстовая ссылка:
      Она выглядит вот так: Как создать свой сайт
    3. BB-код ссылки для форумов (например, можете поставить её в подписи):

    Комментарии ( 0 ):

    Для добавления комментариев надо войти в систему.
    Если Вы ещё не зарегистрированы на сайте, то сначала зарегистрируйтесь.

    Copyright © 2010-2023 Русаков Михаил Юрьевич. Все права защищены.

    Источник

    Читайте также:  Exec cmd in python
    Оцените статью