瀏覽器都有頁面全屏的功能 F11 ,那么如何用JavaScript控制頁面全屏呢?MDN上提供的的API , 一個小demo驗證一下!
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>全屏</title> <style> html, body { height: 100%; } img { display: block; margin: 100px auto 0; width: 900px; cursor: pointer; } /* webkit和IE在元素進入全屏后,會保持元素原有的尺寸,所以需要通過css偽類進行設置 */ img:-webkit-full-screen{ width: 100%; height: 100%; } img:-ms-fullscreen { width: 100%; height: 100%; } </style> </head> <body> <img id="target" src="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1530343927072&di=ba9a25dc1d88a14556abf44106a32a4f&imgtype=0&src=http%3A%2F%2Fup.enterdesk.com%2Fedpic_source%2Fe9%2F3d%2Ffc%2Fe93dfc90c7406e68dd72afac6dda0357.jpg" alt=""> <script> window.onload = function () { let img = document.querySelector('#target'); // 監聽事件 注意不同瀏覽器的兼容性問問題
// 錯誤事件為:fullscreenerror , 同樣注意前綴
document.addEventListener('fullscreenchange' , function() { console.log('全屏切換!') }) document.addEventListener('webkitfullscreenchange' , function() { console.log('全屏切換!') }) document.addEventListener('mozfullscreenchange' , function() { console.log('全屏切換!') }) document.addEventListener('MSFullscreenChange' , function() { console.log('全屏切換!') })
// 圖片點擊切換全屏 if (isFUllScreenEnabled()) { img.addEventListener('click', function () { if (hasFullScreenElement()) { exitFullScreen(); } else { setFullScreen(img); } }); } else{ console.log('此瀏覽器不支持全屏'); } } // 判斷瀏覽器是否支持全屏 function isFUllScreenEnabled() { return document.fullscreenEnabled || document.webkitFullscreenEnabled || document.mozFullScreenEnabled || document.msFullscreenEnabled; } // 判斷是否有已全屏的元素 function hasFullScreenElement() { return document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement } // 將目標元素設置為全屏展示 function setFullScreen(target) { if (target.requestFullscreen) { target.requestFullscreen(); } if (target.webkitRequestFullscreen) { target.webkitRequestFullscreen(); } if (target.mozRequestFullScreen) { target.mozRequestFullScreen(); } if (target.msRequestFullscreen) { target.msRequestFullscreen(); } } // 文檔退出全屏 function exitFullScreen() { if (document.exitFullscreen) { document.exitFullscreen(); } if (document.webkitExitFullscreen) { document.webkitExitFullscreen(); } if (document.mozCancelFullScreen) { document.mozCancelFullScreen(); } if (document.msExitFullscreen) { document.msExitFullscreen(); } } </script> </body> </html>
Api的使用都很簡單,主要就是一個兼容性的問題,這個小demo,在Chrome,Firefox,Edge,IE 11 上測試過,都可以正常切換全屏,也可以正常監聽事件。
要注意Firefox中方法的拼寫,F為大寫(囧 , 報錯了看了半天,原來是拼寫錯誤),Chrome和IE的記得要加CSS偽類去設置樣式。