gpt4 book ai didi

javascript - "fullscreenchange"事件与所有浏览器不兼容(寻找 Vanilla Javascript 修复)

转载 作者:行者123 更新时间:2023-11-30 19:26:54 27 4
gpt4 key购买 nike

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

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

如何使用普通 javascript 让这段代码在所有浏览器中工作?

最佳答案

this documentation 中所述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");
}
});
});

关于javascript - "fullscreenchange"事件与所有浏览器不兼容(寻找 Vanilla Javascript 修复),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56809298/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com