H5 中禁止横屏或竖屏,锁定屏幕旋转

1,612 阅读1分钟

百度和 Google 了半天,没有找到正确且合适的解决方案,还是官方文档靠谱,最终解决了我的问题,最关键的方法就是 screen.orientation.lock()

官方 demo

<script>
function updateLockButton() {
  const lockButton = document.getElementById("button");
  const newOrientation = getOppositeOrientation();
  lockButton.textContent = `Lock to ${newOrientation}`;
}

function getOppositeOrientation() {
  return screen
    .orientation
    .type
    .startsWith("portrait") ? "landscape" : "portrait";
}

async function rotate(lockButton) {
	// 注:只有全屏才能禁止横屏或竖屏
  if (!document.fullscreenElement) {
    await document.documentElement.requestFullscreen();
  }
  const newOrientation = getOppositeOrientation();
  await screen.orientation.lock(newOrientation);
  updateLockButton(lockButton);
}

screen.orientation.addEventListener("change", updateLockButton);

window.addEventListener("load", updateLockButton);
</script>

<button onclick="rotate(this)" id="button">
  Lock to...
</button>
<button onclick="screen.orientation.unlock()">
  Unlock
</button>

报错及解决思路

报错1

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

直接调用 document.documentElement.requestFullscreen() 会报该错误,必须在用户点击之后才能调用。

报错2

DOMException: screen.orientation.lock() is not available on this device.

说明浏览器不支持该方法,得找其他的方法实现,我用华为手机的浏览器测试是没问题的,其他浏览器得根据具体情况来看。