天天看點

針對html元素的全屏實作

這是個很棒的功能。一般我們都是直接針對網頁來實作,等同與F11的功能。

但是今天發現個好玩的,可以針對某元素實作全屏⊙_⊙

這就很6了,有了它我們就能實作類似元素視覺聚焦,如HTML5全屏等╮(╯▽╰)╭

實作原理,主要靠浏覽器提供的API支援

首先是w3c标準的

// 全屏
element.requestFullScreen();
// 退出全屏
document.exitFullscreen();
           

而各家浏覽器的私有支援的

// Chrome
document.webkitCancelFullScreen();
// 火狐
document.mozRequestFullScreen();
           

這情況嘛,當然是做相容處理啦~

//  做個全屏的構造函數
var FullScreen = function(elem){
  this.elem = document.querySelector(elem);
}
//  全屏
FullScreen.prototype.in = function() {  
    if (this.elem.requestFullscreen) {
      this.elem.requestFullscreen();
    } else if (this.elem.webkitRequestFullscreen) {
      this.elem.webkitRequestFullscreen();
    } else if (this.elem.mozRequestFullScreen) {
      this.elem.mozRequestFullScreen();
    } else if (this.elem.msRequestFullscreen) {
      //  IE的實作沒有實測過,不過據網上的資料說IE11以下可實作的
      this.elem.msRequestFullscreen();
    }
}
//  退出全屏
FullScreen.prototype.out = function() {  
    if (document.exitFullscreen) {
      document.exitFullscreen();
    } else if (document.webkitExitFullscreen) {
      document.webkitExitFullscreen();
    } else if (document.mozCancelFullScreen) {
      document.mozCancelFullScreen();
    } else if (document.msExitFullscreen) {
      document.msExitFullscreen();
    }
}
           

當我們使用的時候,new一個就好了

var test = new FullScreen(".test");
//  全屏
test.in();
//  退出
test.out();
           

補充說明,測試過程中發現個bug:元素全屏和網頁全屏(F11)的退出會沖突…暫時思路是在元素屏蔽的期間屏蔽網頁全屏的鍵盤事件