30秒学会 JavaScript 片段 · 2023年12月21日

30秒学会 JavaScript 片段 – Toggle fullscreen mode

Opens or closes an element in fullscreen mode.

  • Use Document.querySelector() and Element.requestFullscreen() to open the given element in fullscreen.
  • Use Document.exitFullscreen() to exit fullscreen mode.
  • Omit the second argument, el, to use body as the default element.
  • Omit the first element, mode, to open the element in fullscreen mode by default.

代码实现

const fullscreen = (mode = true, el = 'body') =>
  mode
    ? document.querySelector(el).requestFullscreen()
    : document.exitFullscreen();

fullscreen(); // Opens `body` in fullscreen mode
fullscreen(false); // Exits fullscreen mode

翻译自:https://www.30secondsofcode.org/js/s/fullscreen