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

最佳答案

一旦页面加载,就会应用全屏外样式规则。
因为这个密码:

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);
}

关于javascript - 寻找一种更有效的方式来编写此Javascript,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14848481/

10-13 06:03