1

我正在使用“fullscreenchange”事件来应用我想要的 css,方法是添加或删除一个 ID ( #showFullscreen),该 ID () 将支配已经应用到的 css .fullscreen

    var fullscreen = document.getElementsByClassName("fullscreen");

    document.addEventListener("fullscreenchange", function() {
        if (document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement) {
            fullscreen[0].setAttribute("id", "showFullscreen");
        } else if (!document.fullscreenElement || !document.webkitFullscreenElement || !document.mozFullScreenElement || !document.msFullscreenElement) {
            fullscreen[0].removeAttribute("id", "showFullscreen");
        }
     });

如何使用 vanilla javascript 让此代码在所有浏览器中工作?

4

1 回答 1

4

本文档bij W3Schools 中所述,您需要根据浏览器为事件名称添加前缀。

// Includes an empty string because fullscreenchange without prefix is
// also a valid event we need to listen for
const prefixes = ["", "moz", "webkit", "ms"]
var fullscreen = document.getElementsByClassName("fullscreen");
var fullscreenElement = document.fullscreenElement || /* Standard syntax */
  document.webkitFullscreenElement || /* Chrome, Safari and Opera syntax */
  document.mozFullScreenElement || /* Firefox syntax */
  document.msFullscreenElement /* IE/Edge syntax */;

prefixes.forEach(function(prefix) {
 document.addEventListener(prefix + "fullscreenchange", function() {
    if (fullscreenElement) {
        fullscreen[0].setAttribute("id", "showFullscreen");
    } else if (!document.fullscreenchange) {
        fullscreen[0].removeAttribute("id", "showFullscreen");
    }
 });
});
于 2019-06-29T21:40:38.080 回答