2015年3月8日日曜日

JavaScriptでフルスクリーン終了・エレメント取得も [ WEB ]

前回、requestFullscerrn()メソッドを追加を試したので、今回は、フルスクリーンの終了とエレメント取得も追加しておこう、Internet Explorer Dev Centerのソースを見るとベンター毎にFullScreenかFullscreenか(Sが大文字か小文字か)で微妙にちがうな。
前回のものと合体して、書きなおしておく。
今回はいっぱい書くのが面倒なのでjQueryも使った。
Element.prototype.requestFullscreen = Element.prototype[(
 Element.prototype.requestFullscreen ||
 Element.prototype.msRequestFullscreen ||
 Element.prototype.webkitRequestFullScreen ||
 Element.prototype.mozRequestFullScreen ||
 {name:null}).name] || function(){};

document.exitFullscreen = 
 document.exitFullscreen ||
 document.msExitFullscreen ||
 document.webkitExitFullscreen ||
 document.mozCancelFullScreen ||
 function(){};

if(!document.fullscreenElement)
 document.__defineGetter__("fullscreenElement", function(){
  return(
   document.msFullscreenElement ||
   document.webkitFullscreenElement ||
   document.mozFullScreenElement || null);
 });
上記のコードをJavascriptの先頭の方にいれておけば良い。ここまではjQueryは必要ないよ。
exitFullscreen()はdocumentオブジェクトの呼び出しだったので、そのまま上書きした。ちなみにwebkitには、webkitCancelFullScreen()ってのもあるみたい(Sが大文字)で、動作は同じ。
fullscreenElementプロパティはgetterを使って、上書きしておいた。
あ、それと、fullscreenElementnull なら、フルスクリーン表示中ではないとわかるらしい。
これで、requestFullscreen()exitFullscreen()fullscreenElementが使えるようになるはず。
Javascriptすげーな、なんでも実装できちゃうね★
<!DOCTYPE html>
<html>
 <head>
 <script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
 <script src="fullscreen.js"></script>
 </head>
 <body>
  <div id="fullScreen">
   <h3>Full Screen Demo</h3>
   <p>MODE:<span id="mode">NORMAL SCREEN</span></p>
   <button id="elem">FullscreenElement</button>
   <button id="full">RequestFullscreen()</button>
   <button id="exit">ExitFullscreen()</button>
  </div>
 </body>
</html>
Element.prototype.requestFullscreen = Element.prototype[(
 Element.prototype.requestFullscreen ||
 Element.prototype.msRequestFullscreen ||
 Element.prototype.webkitRequestFullScreen ||
 Element.prototype.mozRequestFullScreen ||
 {name:null}).name] || function(){};

document.exitFullscreen = 
 document.exitFullscreen ||
 document.msExitFullscreen ||
 document.webkitExitFullscreen ||
 document.mozCancelFullScreen ||
 function(){};

if(!document.fullscreenElement)
 document.__defineGetter__("fullscreenElement", function(){
  return(
   document.msFullscreenElement ||
   document.webkitFullscreenElement ||
   document.mozFullScreenElement || null);
 });


// 以下jQueryが必要
$(function(){
 var bg;
 $("#elem").click(function(){
  bg = (bg!="blue")?"blue":"red";
  $(document.fullscreenElement).css("background",bg);
 });
 $("#full").click(function(){
  $("#fullScreen")[0].requestFullscreen();
  $("#mode").text("FULL SCREEN");
 });
 $("#exit").click(function(){
  document.exitFullscreen();
  $("#mode").text("NORMAL SCREEN");
 });
});
動作は、「FullscreenElement」ボタンはフルスクリーンの時しか動作せず、青と赤が切り替わるはず。

追記:defineProperty()の方がいいみたい。
修正:2016/02/09 [fullscreen.js : Line 19] FullscreenElement → fullscreenElement

ふんどしの持ち主

0 件のコメント:

コメントを投稿