全屏api
主要方法
- document.exitFullscreen(); ????????退出頁面全屏狀態,document是全局文檔對象
dom.requestFullscreen();? ? ? ? ? ? 使dom進入全屏狀態,異步,dom是一個dom元素
dom.onfullscreenchange();? ? ?全屏狀態變化時觸發事件
主要屬性
- document.fullscreenElement; 返回當前全屏的dom元素,若沒有則返回null
?css相關偽類
?:fullscreen CSS 偽類當元素處于全屏時生效
?全屏實例
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><style>p{background-color: #ccc;}p:fullscreen{background-color: #ffd0d0;}</style>
</head><body><p id="dom"><button onclick="fullScreen()" id="bt">進入全屏</button><br> Element.requestFullscreen() 方法用于發出異步請求使元素進入全屏模式。調用此 API 并不能保證元素一定能夠進入全屏模式。如果元素被允許進入全屏幕模式,返回的Promise會 resolve,并且該元素會收到一個fullscreenchange事件,通知它已經進入全屏模式。如果全屏請求被拒絕,返回的promise 會變成 rejected 并且該元素會收到一個fullscreenerror事件。如果該元素已經從原來的文檔中分離,那么該文檔將會收到這些事件。<br>只讀屬性 Document.fullscreenElement 返回當前頁面中以全屏模式呈現的 Element,如果當前頁面未使用全屏模式,則返回 null。返回當前處于全屏模式的 Element 對象;如果當前頁面未使用全屏模式,則返回 null。<br>:fullscreen CSS 偽類匹配當前處于全屏模式的所有元素。如果有多個元素被放置在全屏模式下,則此選擇器將匹配所有這些元素。</p>
</body>
<script>const dom = document.getElementById('dom');const bt = document.getElementById('bt');function fullScreen() {dom.requestFullscreen();}dom.onfullscreenchange = (e)=>{// // 清除默認事件// e.preventDefault();// document.fullscreenElement ? console.log('進入全屏') : console.log('退出全屏');console.log(document.fullscreenElement);if(document.fullscreenElement){fullScreen = ()=>{document.exitFullscreen();bt.innerText = '進入全屏'}}else{fullScreen = ()=>{dom.requestFullscreen();bt.innerText = '退出全屏'}}}
</script>
</html>
使用全屏api時要注意,哪些是靜態方法,哪些是實例方法,
同時,不同的瀏覽器進入全屏和退出全屏有兼容性差異,可以在方法前加上對應的前綴