js全屏和自定义全屏样式

在做音视频的时候,需要对页面元素做全屏切换,总结了一个比较实用的方法;分享给社区需要的同学;

设置全屏方法
function launchFullscreen(element) {
  if(element.requestFullscreen) {
    element.requestFullscreen();
  } else if(element.mozRequestFullScreen) {
    element.mozRequestFullScreen();
  } else if(element.msRequestFullscreen){
    element.msRequestFullscreen();
  } else if(element.webkitRequestFullscreen) {
    element.webkitRequestFullScreen();
  }
}

launchFullscreen(document.documentElement);
launchFullscreen(document.getElementById("videoElement"));
css样式修改
:-webkit-full-screen{
    /*你要重置的样式*/
}
:-moz-full-screen {
}
取消全屏方法
function exitFullscreen() {
  if (document.exitFullscreen) {
    document.exitFullscreen();
  } else if (document.msExitFullscreen) {
    document.msExitFullscreen();
  } else if (document.mozCancelFullScreen) {
    document.mozCancelFullScreen();
  } else if (document.webkitExitFullscreen) {
    document.webkitExitFullscreen();
  }
}
exitFullscreen();
判断某个element是否全屏
function isElementFullScreen(element) {
return (document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement) === element; 
}
判断是否全屏
// 如果当前没有节点处于全屏状态,则返回null
var fullscreenElement =
  document.fullscreenElement ||
  document.mozFullScreenElement ||
  document.webkitFullscreenElement;
function isFullScreen() {
    return (document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement) !== null;
}
全局监听
// fullscreenchange事件:浏览器进入或离开全屏时触发。
// fullscreenerror事件:浏览器无法进入全屏时触发,可能是技术原因,也可能是用户拒绝
document.addEventListener("fullscreenchange", function( event ) {
  if (document.fullscreenElement) {
    console.log('进入全屏');
  } else {
    console.log('退出全屏');
  }
});

你可能感兴趣的:(javascript)