如题,在做手机端页面时会遇到需要固定横屏显示的页面,很多人的做法是直接给一个横屏提醒,我也不例外。不过大佬给了我一个新的思路,让页面不管是横着拿着还是竖着拿着都是横屏显示。
思路:监听页面的orientation,也即方向变化。当为竖屏时,页面的高度为原来的宽度,宽度为原来的高度,并通过rotate使页面旋转,可参考css代码。由于旋转需要在中心位置,所以需要绝对定位将页面往下和右偏移50%,再通过translate移回原来位置,这样就实现了横竖屏切换的问题了。
以下是代码:
CSS:
#screen-change{position:absolute;left:50%;top:50%;overflow:hidden;z-index:10}
#screen-change.w{height:100vw;width:100vh;transform:translate(-50%,-50%) rotate(90deg);-webkit-transform:translate(-50%,-50%) rotate(90deg)}
#screen-change.h{height:100vh;width:100vw;transform:translate(-50%,-50%);-webkit-transform:translate(-50%,-50%)}
JS:
! function () {
var viewport = document.getElementById('viewport');
var dw = null;
var screenChange = document.getElementById('screen-change');
function a() {
if (document.body.clientHeight > document.body.clientWidth) {
dw = 750; //页面的高度
screenChange.classList.remove('h');
screenChange.classList.add('w');
} else if (document.body.clientHeight < document.body.clientWidth) {
dw = 1334; //页面的宽度
}
viewport.setAttribute('content', 'width=' + dw + ', user-scalable=no')
}
a();
window.addEventListener("orientationchange", function () {
if (window.orientation == 0) {
screenChange.classList.remove('h');
screenChange.classList.add('w');
dw = 750; //页面的高度
viewport.setAttribute('content', 'width=' + dw + ', user-scalable=no')
} else if (window.orientation == 90) {
screenChange.classList.remove('w');
screenChange.classList.add('h');
dw = 1334; //页面的宽度
viewport.setAttribute('content', 'width=' + dw + ', user-scalable=no')
}
}, false);
}(window);
HTML:直接给body或者在所有标签外面套一层div,给这层元素加上id="screen-change"和class="h",并且在viewport meta标签内添加id="viewport",如
<meta name="viewport" id="viewport" content="initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no">
<body id="screen-change" class="h">
<div>我要横屏显示</div>
</body>