pyList

js实现浏览器全屏方法

浏览器全屏在某些环境下体验很好,特别是小屏幕手机,地址栏占用的空间很多。

js 全屏函数

function launchFullscreen(element) {
    if(element.requestFullscreen) {
        element.requestFullscreen();
    } else if(element.mozRequestFullScreen) {
        element.mozRequestFullScreen();
    } else if(element.webkitRequestFullscreen) {
        element.webkitRequestFullscreen();
    } else if(element.msRequestFullscreen) {
        element.msRequestFullscreen();
    }
}

某个元素全屏调用函数:

launchFullscreen(document.getElementById("goFS"));

全页面全屏:

launchFullscreen(document.documentElement);

考虑到浏览器兼容,整页面全屏可以用下面的函数:

function toggleFullScreen() {
  var doc = window.document;
  var docEl = doc.documentElement;

  var requestFullScreen = docEl.requestFullscreen || docEl.mozRequestFullScreen || docEl.webkitRequestFullScreen || docEl.msRequestFullscreen;
  var cancelFullScreen = doc.exitFullscreen || doc.mozCancelFullScreen || doc.webkitExitFullscreen || doc.msExitFullscreen;

  if(!doc.fullscreenElement && !doc.mozFullScreenElement && !doc.webkitFullscreenElement && !doc.msFullscreenElement) {
    requestFullScreen.call(docEl);
  }
  else {
    cancelFullScreen.call(doc);
  }
}

应注意的是,FullScreen 函数只能由用户动作触发,不能自动调用。否则会出现下面错误提示:

Failed to execute 'requestFullscreen' on 'Element': API can only be initiated by a user gesture.

参考

本文网址: https://pylist.com/t/1563927923 (转载注明出处)
如果你有任何建议或疑问可以在下面 留言
Be the first to comment!
Captcha image
Relative Articles