1000字范文,内容丰富有趣,学习的好帮手!
1000字范文 > 手机上如何让页面强制横屏

手机上如何让页面强制横屏

时间:2021-09-12 03:23:22

相关推荐

手机上如何让页面强制横屏

首先准备一段html内容:

<div id="content"><p>谁说html5不能横屏的。。。</p><p>我就是要横屏。。。</p><p>要横屏。。。</p><p>横屏。。。</p><p>屏。。。</p><p>图片也是可以的。<img src="http://img001./photos/album/0904/o/6A7A403C29766CBCB38C616BDFD48486.jpg" /></p></div>

其实原理很简单,只需要把内容向右旋转90度就变成了横屏啊。先把定位修改为absolute

#content {position: absolute;top: 0;left: 0;width: 100%;height: 100%;}#content p {margin: auto;margin-top: 20px;text-align: center;}img {width: 100px;}

其实除了position: absolute;这行代码其他都是不必要的,其他只是为了做一些居中对齐等。然后我们用js判断是竖屏(portrait)还是横屏(landscape),如果是竖屏,向右旋转90度。

const width = document.documentElement.clientWidth;const height = document.documentElement.clientHeight;if (width < height) {console.log(width + " " + height);const contentDOM = document.getElementById('content');contentDOM.style.width = height + 'px';contentDOM.style.height = width + 'px';contentDOM.style.top = (height - width) / 2 + 'px';contentDOM.style.left = 0 - (height - width) / 2 + 'px';contentDOM.style.transform = 'rotate(90deg)';}

但是如果用户的屏幕旋转按钮开着,然后用户又把手机横过来,就悲剧了,如下图。

所以我们还需要监听屏幕变化,如果用户自己把屏幕横过来,就把之前的旋转去掉。

const evt = "onorientationchange" in window ? "orientationchange" : "resize";window.addEventListener(evt, function () {const width = document.documentElement.clientWidth;const height = document.documentElement.clientHeight;const contentDOM = document.getElementById('content');alert('width: ' + width + ' height: ' + height)if (width > height) {// 横屏contentDOM.style.width = width + 'px';contentDOM.style.height = height + 'px';contentDOM.style.top = '0px';contentDOM.style.left = '0px';contentDOM.style.transform = 'none';}else {// 竖屏,这里微信应该由bug,我切换为竖屏的时候,width:375, height: 323, 导致不能旋转角度。 在safari、chrome上是正确的。alert('change to portrait')contentDOM.style.width = height + 'px';contentDOM.style.height = width + 'px';contentDOM.style.top = (height - width) / 2 + 'px';contentDOM.style.left = 0 - (height - width) / 2 + 'px';contentDOM.style.transform = 'rotate(90deg)';}}, false);

完整的Demo请看这里。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。