/* 2021.11.23 编写点击全屏和取消全屏的功能 */
$('.fullorCancel').click(function(){
let that = $(this);
let flagHave = that.hasClass('fullScreenVal');
if(flagHave){
window.localStorage.setItem('fullscreenFlag', 'TRUE');
let el = document.documentElement;
let ref = el.requestFullScreen || el.webkitRequestFullScreen || el.mozRequestFullScreen || el.msRequestFullscreen; //各个浏览器的兼容性
if(typeof ref !== 'undefined' && ref){
ref.call(el);
that.removeClass('fullScreenVal');
that.html('');
that.attr('title', '取消全屏');
}else{
console.log('全屏失败');
}
}else{
window.localStorage.setItem('fullscreenFlag', 'FALSE');
if(document.exitFullscreen){
document.exitFullscreen();
that.addClass('fullScreenVal');
that.html('');
that.attr('title', '全屏');
}else if(document.mozCancelFullScreen){
document.mozCancelFullScreen();
that.addClass('fullScreenVal');
that.html('');
that.attr('title', '全屏');
}else if(document.webkitExitFullscreen){
document.webkitExitFullscreen();
that.addClass('fullScreenVal');
that.html('');
that.attr('title', '全屏');
}else if(document.msExitFullscreen){
document.msExitFullscreen();
that.addClass('fullScreenVal');
that.html('');
that.attr('title', '全屏');
}else{
console.log('浏览器不兼容');
}
}
});
function addLister(val){
let isFull = document.webkitFullscreenElement||
document.mozFullScreenElement||
document.msFullscreenElement;
if(isFull){
console.log('webkit');
$('#judgeFullOrCancel').removeClass('fullScreenVal');
$('#judgeFullOrCancel').html('');
$('#judgeFullOrCancel').attr('title', '取消全屏');
}else{
$('#judgeFullOrCancel').addClass('fullScreenVal');
$('#judgeFullOrCancel').html('');
$('#judgeFullOrCancel').attr('title', '全屏');
}
}
/* 2021.11.23 监听取消全屏 */
document.addEventListener('webkitfullscreenchange', addLister);
document.addEventListener('fullscreenchange', addLister);
document.addEventListener('mozfullscreenchange', addLister);
document.addEventListener('msfullscreenchange', addLister);
/* 2021.11.23 监听是否点击了F11按钮 */
document.onkeydown=function(event){
var e = event || window.event || arguments.callee.caller.arguments[0];
if(e && e.keyCode==122){ // 按 F11
e.preventDefault();//阻止默认事件
e.stopPropagation();
let el = document.documentElement;
let ref = el.requestFullScreen || el.webkitRequestFullScreen || el.mozRequestFullScreen || el.msRequestFullscreen;
if(typeof ref !== 'undefined' && ref){
ref.call(el);
$('#judgeFullOrCancel').removeClass('fullScreenVal');
$('#judgeFullOrCancel').html('');
$('#judgeFullOrCancel').attr('title', '取消全屏');
}else{
console.log('全屏失败');
}
}
}
以上点击事实现了页面的全屏与取消全屏,并且成功监听了F11 与 esc按键的全屏与取消全屏事件。 但是此方法有个bug, 就是页面刷新或者切换的时候,会自动取消全屏。请问,如何修改,能实现页面在刷新和切换新页面的时候,不自动取消全屏?