H5 - 强制横屏
1、常用的小游戏开发挺多都是横屏显示,所以我们H5开发同样也需要横屏显示,所以我分享一个强制横屏的demo,html的内容如下:
<body style="margin: 0px;height: 100%;padding: 0;" > <div id="print"> <div id="changeIt"> 11111111 </div> </div> </body>
2、通过媒体查询,区分在横屏和竖屏的状态下使用的css,代码如下:
/* 竖屏 orientation: portrait 代表竖屏的状态下*/ @media screen and (orientation: portrait) { html { width: 100%; height: 100%; overflow: hidden; } body { width: 100%; height: 100%; overflow: hidden; } #print { position: absolute; } } /* 横屏 orientation: landscape代表手机在横屏的状态下 */ @media screen and (orientation: landscape) { html { width: 100%; height: 100%; } body { width: 100%; height: 100%; } #print { position: absolute; top: 0; left: 0; width: 100%; height: 100%; } }
3、接下来是js代码,大家可以手动拷贝一份:
<script> // 试试横屏 let width = document.documentElement.clientWidth; let height = document.documentElement.clientHeight; if (width < height) { console.log(width + "," + height); $print = $('#print'); $print.width(height); $print.height(width); $print.css('top', (height - width) / 2); $print.css('left', 0 - (height - width) / 2); $print.css('transform', 'rotate(90deg)'); $print.css('transform-origin', '50% 50%'); } var evt = "onorientationchange" in window ? "orientationchange" : "resize"; console.log(evt, 'evt') window.addEventListener(evt, function() { setTimeout(function() { var width = document.documentElement.clientWidth; var height = document.documentElement.clientHeight; $print = $('#print'); $videoIntroduce = $('#videoIntroduce') $toVideoBack = $('#toVideoBack') $backgroundImg = $('.backgroundImg') if (width > height) { $print.width(width); $print.height(height); $print.css('top', '0'); $print.css('left', 0); $print.css('transform', 'none'); $print.css('transform-origin', '50% 50%'); } else { $print.width(height); $print.height(width); $print.css('top', (height - width) / 2); $print.css('left', 0 - (height - width) / 2); $print.css('transform', 'rotate(90deg)'); $print.css('transform-origin', '50% 50%'); } }, 500) }, false); </script>
4、我们先用浏览器手机模式测试一下,效果图如下(横屏跟竖屏都是横屏的模式): --真机测试同样也达到了强制横屏的效果
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· 百万级群聊的设计实践
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性
· 全网最简单!3分钟用满血DeepSeek R1开发一款AI智能客服,零代码轻松接入微信、公众号、小程
· .NET 10 首个预览版发布,跨平台开发与性能全面提升
· 《HelloGitHub》第 107 期