在全屏模式下,如何用HTML实现重定向?
标题几乎不言自明:在全屏状态下,如何在HTML中进行重定向?我知道这里有人问过:在Chrome的全屏状态下离开全屏的导航网站,但我在想它是否可以被绕过?
基本上,当按钮被点击时,页面应同时进入全屏并进行重定向。
<script>
button.onclick = function() {
if (document.documentElement.requestFullscreen) {
document.documentElement.requestFullscreen().then(() => {
// Navigate after entering fullscreen
window.location.replace('/whereIWantToGo.html');
});
} else {
window.location.replace('/whereIWantToGo.html');
}
};
</script>
解决方案
采用SPA(单页应用)风格,动态加载内容。类似如下:
<button id="button">Start</button>
<div id="app"></div>
<script>
button.onclick = async function() {
await document.documentElement.requestFullscreen();
document.getElementById("app").innerHTML = `
<h1>New Page Content</h1>
<p>This replaced the page without leaving fullscreen.</p>
`;
};
</script>
页面实际上并不会真正改变。
或者,另一种做法是在导航后再次请求全屏,如下:
document.body.addEventListener("click", () => {
document.documentElement.requestFullscreen();
});
放在下一页执行,但这比较棘手,因为浏览器要求进行新的用户交互,所以不能自动完成。
只要避免导航,改为切换内容即可。
我相信你知道浏览器为何强制这样。但这里有我的技巧,我曾经做过一个网页游戏,使用这个不错的技巧,我在更改内容的同时也修改了URL,使用 history.pushState(),大致像这样:
<button id="start">Start</button>
<div id="app">
<h1>Home Page</h1>
</div>
然后在JS中,我
const startBtn = document.getElementById("start");
const app = document.getElementById("app");
startBtn.onclick = async () => {
// this to enter fullscreen
await document.documentElement.requestFullscreen();
// this to change URL without redirect
history.pushState({}, "", "/game");
// this to replace page content
app.innerHTML = `
<h1>Game Page</h1>
<p>You are still fullscreen.</p>
`;
};
因此例如如果URL改变为 /game,全屏仍然保持,但内容会更新。现在如果你想返回,你需要检测浏览器的后退导航,你可以简单地这样做:
window.onpopstate = () => {
app.innerHTML = "<h1>Home Page</h1>";
};
这样后退按钮就能正常工作。我在某处看到过,像figma和 youtube等平台就使用类似的办法。或者更好地,创建一个小路由器。希望以上方法对你有帮助。
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。