2

有没有更好的方法让我写toggleFullscreen(). 我在每个浏览器上重复样式规则,这似乎非常不必要。

function toggleFullScreen() {   
  var elem = document.getElementById("video_container");
  var db = document.getElementById("defaultBar"); 
  var ctrl = document.getElementById("controls");

  if (!document.fullscreenElement &&    // alternative standard method
      !document.mozFullScreenElement && !document.webkitFullscreenElement) {  // current working methods
    if (document.documentElement.requestFullscreen) {
          db.style.background ='red';
          ctrl.style.width = '50%';
          ctrl.style.left = '25%';
          elem.requestFullscreen();
        } else if (document.documentElement.mozRequestFullScreen) {
          db.style.background ='red';
          ctrl.style.width = '50%';
          ctrl.style.left = '25%';
          elem.mozRequestFullScreen();
        } else if (document.documentElement.webkitRequestFullscreen) {
          db.style.background ='red';
          ctrl.style.width = '50%';
          ctrl.style.left = '25%';
          elem.webkitRequestFullscreen();
        }
  } else if (document.exitFullscreen) {
        db.style.background ='yellow';
        ctrl.style.width = '100%';
        ctrl.style.left = '0';        
        document.exitFullscreen();
        }
        else if (document.mozCancelFullScreen) {
        db.style.background ='yellow';
        ctrl.style.width = '100%';
        ctrl.style.left = '0'; 
        document.mozCancelFullScreen();
        }
        else if (document.webkitCancelFullScreen) {
        db.style.background ='yellow';
        ctrl.style.width = '100%';
        ctrl.style.left = '0';
        document.webkitCancelFullScreen();
        } 
}
4

1 回答 1

3

页面加载后立即应用 out of fullScreen 样式规则。

那是因为这段代码:

full.addEventListener('click', toggleFullScreen(), false);

If 立即执行toggleFullScreen()并将返回值传递给addEventListener而不是。代码可能应该是:

full.addEventListener('click', toggleFullScreen, false);

此代码传递对函数的引用而不是其返回值。

重构

通过使用||运算符,您可以大大简化现有条件。

var fullScreenElement = document.fullscreenElement || document.mozFullScreenElement || document.webkitFullscreenElement;

if (fullScreenElement) {
  var requestFullScreen = document.documentElement.requestFullscreen || document.documentElement.mozRequestFullScreen || document.documentElement.webkitRequestFullscreen

  db.style.background ='red';
  ctrl.style.width = '50%';
  ctrl.style.left = '25%';
  requestFullScreen.call(elem);
} else {
  var exitFullScreen = document.exitFullscreen || document.mozCancelFullScreen || document.webkitCancelFullScreen;

  db.style.background ='yellow';
  ctrl.style.width = '100%';
  ctrl.style.left = '0';        
  exitFullScreen.call(document);
}
于 2013-02-13T07:33:37.453 回答