我有没有更好的方式写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);
}