注意
1.在< iframe >框架中使用全屏需要加 allowfullscreen 属性。 document.getElementById('iframe').setAttribute('allowFullScreen','')
2.全屏请求只能通过用户操作触发,否则会出现Failed to execute ‘requestFullscreen’ on ‘Element’: API can only be initiated by a user gesture.这样的警告,解决办法是将此方法绑定到某个用户操作事件上,例如点击事件 click 。
// 全屏
const MAZEY_FULL_SCREEN = function () {
var prefixArr = ['', 'webkit', 'moz', 'ms'], // 浏览器前缀
isRightRequest, // 是否找到适配的方法
isRightExit,
requestMethod, // 全屏方法
exitMethod, // 退出全屏方法
lowerFirst = function (str) {
return str.slice(0, 1).toLowerCase() + str.slice(1);
},
requestSuffixArr = ['RequestFullscreen', 'RequestFullScreen'], // 后缀
exitSuffixArr = ['ExitFullscreen', 'CancelFullScreen'],
searchRightMethod = function (prefix, suffixArr, documentParent) {
var methodArr = suffixArr.map(function(suffix) {
return prefix + suffix;
}),
method,
isRight;
methodArr.forEach(function(wholePrefix) {
if (isRight) return;
if (prefix.length === 0) {
wholePrefix = lowerFirst(wholePrefix)
}
if (wholePrefix in documentParent) {
method = wholePrefix;
isRight = true;
// console.log(method);
}
});
return method;
};
prefixArr.forEach(function(prefix){
if (isRightRequest && isRightExit) return;
// 查找请求
requestMethod = searchRightMethod(prefix, requestSuffixArr, document.documentElement);
isRightRequest = Boolean(requestMethod);
// 查找退出
exitMethod = searchRightMethod(prefix, exitSuffixArr, document);
isRightExit = Boolean(exitMethod);
});
this.request = function (element) {
var domEle = document.querySelector(element) || document.documentElement;
domEle[requestMethod]();
};
this.exit = function () {
document[exitMethod]();
};
};
var fullscreen = new MAZEY_FULL_SCREEN();
//定义一个变量进行判断,默认false 非全屏状态
var exitFullscreen = false
// 请求全屏
$(function () {
$('#fullScreen').on('click', function () {
if(exitFullscreen){
fullscreen.exit();
exitFullscreen=false;
$(".screen-btn").removeClass('out-full').addClass('full-screen')//样式
}else {
fullscreen.request();
exitFullscreen=true;
$(".screen-btn").removeClass('full-screen').addClass('out-full')//样式
}
});
})
网友评论