全屏显示图像 - 使用JavaScript / HTML5

时间:2014-06-02 11:58:59

标签: javascript html5 internet-explorer google-chrome

我在网页上有一张图片。当我点击它时,它应该全屏显示。

我有以下代码:

<!doctype html>
<html>
  <head>      
     <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>
    Click Image to display Full Screen...</br>

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

  </body>
</html>

我面临的问题 - 在全屏模式下
1.在所有浏览器上,图像以小尺寸显示(即与浏览器页面上的尺寸相同),而不是原始尺寸。
2.在IE中 - 图像不居中,它显示在全屏的左侧(为什么不居中)。在Chrome中 - 根据需要将其置于中心位置。

1 个答案:

答案 0 :(得分:6)

所以,经过一些试验后找到了解决方案......

解决方案在样式部分:
- 宽度,高度,边距设置为“自动”,
- 但也标记为'!important ' - 这允许您在全屏模式下覆盖网页上图像的内嵌样式。

<!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>