Javascript doOnOrientationChange:无法修复加载页面的错误

我使用.js来避免移动设备的横向视图。 每次将我的设备从纵向旋转到横向时,我都会编辑一个白色的全屏图像,指出“此网站不被视为以横向模式查看,请将您的设备”显示出来。 它工作除了当我加载一个页面,我已经在横向模式。 任何想法如何解决它? 谢谢

 <script> (function() { 'use strict'; var isMobile = { Android: function() { return navigator.userAgent.match(/Android/i); }, BlackBerry: function() { return navigator.userAgent.match(/BlackBerry/i); }, iOS: function() { return navigator.userAgent.match(/iPhone|iPad|iPod/i); }, Opera: function() { return navigator.userAgent.match(/Opera Mini/i); }, Windows: function() { return navigator.userAgent.match(/IEMobile/i); }, any: function() { return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows()); } }; if (isMobile.any()) { doOnOrientationChange(); window.addEventListener('resize', doOnOrientationChange, 'false'); } function doOnOrientationChange() { var a = document.getElementById('alert'); var b = document.body; var w = b.offsetWidth; var h = b.offsetHeight; (w / h > 1) ? (a.className = 'show', b.className = 'full-body') : (a.className = 'hide', b.className = ''); } })(); </script> 

更新:

我尝试添加window.orientation到脚本,但有些错误

 if (orientation === "landscape-primary") { doOnOrientationChange(); window.addEventListener('resize',doOnOrientationChange,'false'); } window.onload(doOnOrientationChange()); 

您需要将doOnOrientationChange()函数移到doOnOrientationChange()之外,然后在doOnOrientationChange()上调用它。 像这样它应该工作:

 <script> function checkMobile() { var isMobile = false; if (navigator.userAgent.match(/Android/i) || navigator.userAgent.match(/BlackBerry/i) || navigator.userAgent.match(/iPhone|iPad|iPod/i) || navigator.userAgent.match(/Opera Mini/i) || navigator.userAgent.match(/IEMobile/i)) { isMobile = true; } return isMobile; } function doOnOrientationChange() { var a = document.getElementById('alert'); var b = document.body; var w = b.offsetWidth; var h = b.offsetHeight; if (checkMobile()) { (w / h > 1) ? (a.className = 'show', b.className = 'full-body') : (a.className = 'hide', b.className = ''); } else { a.className = 'hide'; b.className = ''; } } window.onload = doOnOrientationChange(); window.addEventListener('resize', doOnOrientationChange, 'false'); </script> 
Interesting Posts