接到一个H5小游戏的需求,需要强制H5横屏显示;大概效果如下:

实现原理利用transform将这个父容器在竖屏状态下整体顺时针旋转90º,页面就处于横屏的状态。但是因为旋转元素的基点默认为本身的中心点。所以我们设置一下它的旋转中心为左上角(transform-origin: 0% 0%;),这样页面被“转出了屏幕”停留在屏幕的左侧,最后一步只需要将它往右平移一个屏幕的宽度就刚刚好(left:100vw)。

完整的实现代码如下:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
		<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
		<meta http-equiv="Pragma" content="no-cache" />
		<meta http-equiv="Expires" content="0" />
		<meta http-equiv="X-UA-Compatible" content="ie=edge">
		<style type="text/css">
			body {
				position: fixed;
				width: 100%;
				height: 100%;
				padding: 0;
				margin: 0;
				overflow: hidden;
			}

			#main {
				width: 560px;
				height: 320px;
			}

			@media screen and (orientation: portrait) {

				#main {
					position: absolute;
					width: 100vh;
					height: 100vw;
					top: 0;
					left: 100vw;
					-webkit-transform: rotate(90deg);
					-moz-transform: rotate(90deg);
					-ms-transform: rotate(90deg);
					transform: rotate(90deg);
					transform-origin: 0% 0%;
				}
			}

			@media screen and (orientation: landscape) {
				#main {
					position: absolute;
					top: 0;
					left: 0;
					width: 100vw;
					height: 100vh;
				}
			}
		</style>
	</head>
	<body>
		<body>
			<div id="main">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptatem deserunt obcaecati nisi praesentium ipsa adipisci hic culpa a voluptates tenetur nulla animi! Suscipit cumque delectus labore et animi laboriosam voluptas!</div>
		</body>
		<script type="text/javascript" language="javascript" src="./vconsole.min.js"></script>
	</body>
</html>

 

 

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐