我有一个正在使用的Web应用程序的全屏切换按钮,但是当我打开全屏然后再次关闭时,它会重置用户在页面上的位置。
这很令人不快,因为将视口位置重置到网页顶部会切断用户对应用程序的访问,大约需要一半时间,这要求他们向下滚动。
如何修改全屏切换按钮以通过全屏切换保持用户在页面上的位置?
const application = document.querySelector(".application");
function toggleFullscreen(elem) {
elem = elem || document.documentElement;
if (!document.fullscreenElement && !document.mozFullScreenElement &&
!document.webkitFullscreenElement && !document.msFullscreenElement) {
if (elem.requestFullscreen) {
elem.requestFullscreen();
} else if (elem.msRequestFullscreen) {
elem.msRequestFullscreen();
} else if (elem.mozRequestFullScreen) {
elem.mozRequestFullScreen();
} else if (elem.webkitRequestFullscreen) {
elem.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
}
} else {
if (document.exitFullscreen) {
document.exitFullscreen();
} else if (document.msExitFullscreen) {
document.msExitFullscreen();
} else if (document.mozCancelFullScreen) {
document.mozCancelFullScreen();
} else if (document.webkitExitFullscreen) {
document.webkitExitFullscreen();
}
}
};
document.getElementById("fullscreenbtn").addEventListener("click", function() {
toggleFullscreen(application);
});
html,
body {
padding: 0 !important;
margin: 0 !important;
background: #2d2a2a;
}
#header {
width: 100vw;
height: 10vh;
background: #000;
}
#spacer {
width: 1px;
height: 40vh;
}
#application {
width: 100vw;
height: 95vh;
}
<div id="header"></div>
<div id="spacer"></div>
<button id="fullscreenbtn">fullscreen</button>
<div id="application></div>
(希望如此)您可以看到,全屏切换会将视口重置为页面顶部(不处于全屏模式时)。我宁愿它没有那样做。
答案 0 :(得分:0)
当用户在全屏视图和常规视图之间切换时,请记住window.pageYOffset
位置。将fullscreenchange
事件监听器添加到全局document
中。最重要的是-由于它们都使用不同的事件名称(例如mozfullscreenchange
),因此请在不同的浏览器中进行测试。根据您支持的浏览器列表添加这些监听器。
此处已修改代码,供Chrome浏览器在全屏切换之间跟踪并返回到上一个位置。
const application = document.querySelector(".application");
let screenOffset;
document.addEventListener("fullscreenchange", (event) => {
window.scrollTo(0, screenOffset);
});
document.onfullscreenchange = function ( event ) {
window.scrollTo(0, screenOffset);
};
function toggleFullscreen(elem) {
elem = elem || document.documentElement;
screenOffset = window.pageYOffset;
if (!document.fullscreenElement && !document.mozFullScreenElement &&
!document.webkitFullscreenElement && !document.msFullscreenElement) {
if (elem.requestFullscreen) {
elem.requestFullscreen();
} else if (elem.msRequestFullscreen) {
elem.msRequestFullscreen();
} else if (elem.mozRequestFullScreen) {
elem.mozRequestFullScreen();
} else if (elem.webkitRequestFullscreen) {
elem.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
}
} else {
if (document.exitFullscreen) {
document.exitFullscreen();
} else if (document.msExitFullscreen) {
document.msExitFullscreen();
} else if (document.mozCancelFullScreen) {
document.mozCancelFullScreen();
} else if (document.webkitExitFullscreen) {
document.webkitExitFullscreen();
}
}
};
document.getElementById("fullscreenbtn").addEventListener("click", function() {
toggleFullscreen(application);
});