JavaScript Fullscreen API 跨浏览器兼容封装(Fullscreen API 兼容性列表),免去苦逼写各种浏览器前缀的麻烦。源自 screenfull.js。
以下方法通过 $.AMUI.fullscreen
接口调用。
.request()
使元素全屏。接受一个 DOM 元素作为参数,默认为 html
。
<iframe>
中需要添加 allowfullscreen
属性 (+ webkitallowfullscreen
and moz allowfullscreen
)。
<iframe id="frame1" allowfullscreen mozallowfullscreen webkitallowfullscreen src="iframeTest.html"></iframe>
注意全屏 API 仅能通过用户事件(如 click、touch、key) 初始化。
.exit()
退出全屏模式。
.toggle()
全屏模式切换。
var fullscreen = $.AMUI.fullscreen;
if (fullscreen.enabled) {
document.addEventListener(fullscreen.raw.fullscreenchange, function() {
console.log('Am I fullscreen? ' + (fullscreen.isFullscreen ? 'Yes' : 'No'));
});
}
var fullscreen = $.AMUI.fullscreen;
if (fullscreen.enabled) {
document.addEventListener(fullscreen.raw.fullscreenerror, function(e) {
console.error('Failed to enable fullscreen', e);
});
}
.isFullscreen
布尔值,是否处于全屏模式。
.element
返回当前处于全屏模式的元素,没有则返回 null
。
.enabled
是否允许全屏模式。<iframe>
中的页面需要添加 allowfullscreen
属性 (+ webkitallowfullscreen
and moz allowfullscreen
)。
.raw
返回包含原始方法名称的对象,对象 key
包括: requestFullscreen
, exitFullscreen
, fullscreenElement
, fullscreenEnabled
, fullscreenchange
,fullscreenerror
$(document).on($.AMUI.fullscreen.raw.fullscreenchange, function () {
console.log('Fullscreen change');
});
$('#demo-full-page').on('click', function () {
if ($.AMUI.fullscreen.enabled) {
$.AMUI.fullscreen.request();
} else {
// Ignore or do something else
}
});
<div>
<img id="demo-full-img" src="http://amazeui.p2hp.com/static/images/002.jpg"
width="340"
height="142"
alt=""/>
<br/>
点击图片全屏显示
<br/>
<span id="doc-fs-img"></span>
</div>
var fullscreen = $.AMUI.fullscreen;
$('#demo-full-img').on('click', function () {
if (fullscreen.enabled) {
fullscreen.request(this);
}
}).on(fullscreen.raw.fullscreenchange, function () {
// 监听图片全屏状态
var text = '图片状态:' + (fullscreen.isFullscreen ? '全屏' : '非全屏');
$('#doc-fs-img').html(text);
});
打开控制台,点击上面的演示看看
if (fullscreen.enabled) {
$(document).on($.AMUI.fullscreen.raw.fullscreenchange, function () {
console.log('Am I fullscreen? ' + ($.AMUI.fullscreen.isFullscreen ? 'Yes' : 'No'));
});
}
MIT © Sindre Sorhus