首页 > 解决方案 > 如何知道您的元素处于全屏模式以及如何获取该元素

问题描述

我的网页中有一些元素,每个元素都与一个按钮相关。当它的按钮被点击时,元素进入全屏模式。当这些元素中的每一个都处于全屏模式时,我希望他们做一些事情,但他们必须做的工作对他们每个人来说都是不同的。

<html>
<body>

<button id="button"></button>
<div id="element" style="width:100px;height:100px;background-color:red"></div>

<script>

var fullscreen_the_element = function(passedElementId){

        var element = document.getElementById(passedElementId);
        if(element.requestFullscreen) 
            element.requestFullscreen();
        else if(element.mozRequestFullScreen)   /* Firefox */
            element.mozRequestFullScreen();
        else if(element.webkitRequestFullscreen)   /* Chrome, Safari & Opera */
            element.webkitRequestFullscreen();
        else if(element.msRequestFullscreen)   /* IE/Edge */
            element.msRequestFullscreen();
    }

var btn = document.getElementById('button');

btn.click(function(){
    fullscreen_the_element('button');
});

/* if the div element is in fullscreen mode then change the elements backgound-color to yellow

here i can use the documnet.fullscreen to know if the document is in
 fullscreen mode, but i need to know if this specific element is in fullscreen mode by 
id (because i have many elements that have to go to 
fullscreen mode and also have to execute different code when they are in 
fullscreen mode. the document.fullscreen just tells that the document is in 
fullscreen mode and i wouldn't know that which element is in fullscreen mode, 
because the document is not the element. what should i do here and what 
methods can i use when entering and exiting the fullscreen mode of this 
element and not the document)

*/

<script>
</body>
</html>
  1. 首先我需要知道元素是否处于全屏模式。
  2. 我需要通过它的特定 id 知道哪个元素处于全屏模式(因为每个元素在全屏模式下都有不同的代码要运行)。

我该怎么做这两件事?我也希望您的答案支持所有浏览器(尤其是像 IE 这样的旧的和棘手的浏览器)。(请给我关于代码的足够解释)

谢谢你

标签: javascript

解决方案


全屏模式下一次只能有一个元素。

用于document.fullscreenElement确定某些元素是否处于全屏模式

function fs_status() {
    var fullScreenElement = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement
    return fullScreenElement;
}

// To find id of element
var id
var fs_elem = fs_status()
if(fs_elem != null){
    // No element in full screen
}else {
    // There is an element in fullscreen
    id = fs_elem.id
    // Do some work with element having id
}

推荐阅读