使用单个功能全屏制作多张图像

时间:2019-05-23 12:14:07

标签: javascript html css fullscreen

我在一个关于Stack Overflow的问题中发现了一种代码,该代码可以全屏显示图像,但是该代码仅适用于一张图像。

<!doctype html>
<html>
  <head>
     <style>
      .fullscreen:-webkit-full-screen {
      width: auto !important;
      height: auto !important;
      margin:auto !important;
  }
     .fullscreen:-moz-full-screen {
      width: auto !important;
      height: auto !important;
      margin:auto !important;
  }
     .fullscreen:-ms-fullscreen {
      width: auto !important;
      height: auto !important;
      margin:auto !important;
  }     
     </style>
     <script>
        function makeFullScreen() {
         var divObj = document.getElementById("theImage");
       //Use the specification method before using prefixed versions
      if (divObj.requestFullscreen) {
        divObj.requestFullscreen();
      }
      else if (divObj.msRequestFullscreen) {
        divObj.msRequestFullscreen();               
      }
      else if (divObj.mozRequestFullScreen) {
        divObj.mozRequestFullScreen();      
      }
      else if (divObj.webkitRequestFullscreen) {
        divObj.webkitRequestFullscreen();       
      } else {
        console.log("Fullscreen API is not supported");
      } 

    }
     </script>

  </head>
  <body>
    Hello Image...</br>

    <img id="theImage" style="width:400px; height:auto;"  class="fullscreen" src="pic1.jpg" onClick="makeFullScreen()"></img>

  </body>
</html>

可以将此功能转换为在多张图像上使用(而不是对每张图像都使用一个功能)。

1 个答案:

答案 0 :(得分:1)

只需将onClick处理程序添加到多个图像元素,并将 event 参数分配给每个函数调用即可。

<img src="picA.jpg" onClick="makeFullScreen(event)">
<img src="picB.jpg" onClick="makeFullScreen(event)">
<img src="picC.jpg" onClick="makeFullScreen(event)">

makefullScreen 回调函数中,您可以获取触发click事件的元素(即图像),并使用现有代码将其设置为全屏显示。

function makeFullScreen(e) {
  var divObj = e.currentTarget;
  //Use the specification method before using prefixed versions
  if (divObj.requestFullscreen) {
    divObj.requestFullscreen();
  } else if (divObj.msRequestFullscreen) {
    divObj.msRequestFullscreen();
  } else if (divObj.mozRequestFullScreen) {
    divObj.mozRequestFullScreen();
  } else if (divObj.webkitRequestFullscreen) {
    divObj.webkitRequestFullscreen();
  } else {
    console.log("Fullscreen API is not supported");
  }
}