JavaScript以全屏模式显示元素

点击某个元素的时候让某个元素全屏显示

这段代码定义了一个函数 goToFullScreen(element),用于切换指定元素(或者默认全屏)的全屏模式。该函数支持各种主流浏览器,包括 Chrome、Firefox、Safari 以及 Internet Explorer 和 Edge 等。

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    * {
      margin: 0;
      padding: 0;
      list-style: none;
    }

    html,
    body {
      width: 100%;
      height: 100%;
    }

    .Box {
      width: 100vw;
      height: 100vh;
      background: #ccc;
    }

    #imgSrc {
      width: 300px;
      height: auto;
    }
  </style>
</head>

<body>
  <div class="Box">

    <img id="imgSrc"
      src="https://ts1.cn.mm.bing.net/th?id=OIP-C.mH9YLFEL5YdVxJM82mjVJQHaEo&w=316&h=197&c=8&rs=1&qlt=90&o=6&pid=3.1&rm=2"
      alt="">

    <button class="scrallFall">点击让图片进行全屏显示</button>

  </div>
</body>
<script>


  const goToFullScreen = (element) => {// 定义名为 "goToFullScreen" 的函数,并接受一个参数 "element"。
    element = element || document.body;// 如果传入 "element" 参数则以该元素为目标,否则为整个文档体 "document.body"
    if (element.requestFullscreen) {// 判断是否支持 W3C 标准的请求全屏接口
      element.requestFullscreen();// 通过调用 requestFullscreen() 方法来请求进入全屏模式
    } else if (element.mozRequestFullScreen) {// 判断是否支持 moz 的非标准客户端 API 请求接口
      element.mozRequestFullScreen();// 通过调用 mozRequestFullScreen() 方法来请求进入全屏模式
    } else if (element.msRequestFullscreen) {// 判断是否支持 Microsoft 提供的 PC Edge 浏览器和 IE11 浏览器专属 Api 接口
      element.msRequestFullscreen();// 通过调用 msRequestFullscreen() 方法来请求进入全屏模式
    } else if (element.webkitRequestFullscreen) {// 判断是否支持 Webkit 内核标准请求接口
      element.webkitRequestFullScreen();// 通过调用 webkitRequestFullScreen() 方法来请求进入全屏模式
    }
  };
  const img = document.querySelector('#imgSrc');
  const btn = document.querySelector('.scrallFall');
  btn.addEventListener("click", () => {
    goToFullScreen(img);
  });

</script>

</html>

猜你喜欢

转载自blog.csdn.net/m0_63873004/article/details/130502474