JS在第一次输入时停止短路

时间:2016-12-22 14:55:36

标签: javascript fullscreen short-circuiting

我在尝试在我正在制作的网页上使用短路时遇到了一些问题。

我正在尝试使用

document.webkitExitFullscreen() || document.mozCancelFullScreen() || document.exitFullScreen();

但它似乎在第一次尝试时停止了,尽管我会在第一个参数出现之后继续作为未定义。

如果我只是输入

document.mozCancelFullScreen()

然后它工作正常

http://i.imgur.com/rINs1kR.png

我想知道是否有人可以指出我在这里做错了什么 截图是在firefox btw中拍摄的。 提前致谢

2 个答案:

答案 0 :(得分:4)

您的代码正在尝试致电 document.webkitExitFullscreen,如果它返回了假值,致电 document.mozCancelFullScreen等等。

但如果document.webkitExitFullscreen本身为undefined,则在尝试调用它时会出错,并且代码将在此时停止运行。

也许:

var exitFullScreen = document.webkitExitFullscreen || document.mozCancelFullScreen || document.exitFullScreen;
if (exitFullScreen) {
    exitFullScreen.call(document); // Just `exitFullScreen();` may work as well
}

或者:

["webkitExitFullscreen", "mozCancelFullScreen", "exitFullScreen"].some(function(name) {
    if (document[name]) {
        document[name]();
        return true;
    }
});

...这样可以避免整个"我是否需要call?"问题。

答案 1 :(得分:2)

问题是您已经在调用该函数,因此如果它不存在,则会出现错误。 你可以试试像:

(document.webkitExitFullscreen || document.mozCancelFullScreen || document.exitFullScreen)();