寻找一种更有效的方式来编写这个Javascript

时间:2013-02-13 07:29:24

标签: javascript css html5 javascript-events event-listener

有没有更好的方法来编写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();
        } 
}

1 个答案:

答案 0 :(得分:3)

  

一旦页面加载,就会应用out.screen样式规则。

这是因为这段代码:

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

如果立即执行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);
}