之前,做了一个H5项目,需要在横竖屏变化时,做一些处理,一般先要判断手机是否横屏,在不同状态下添加不同效果
方法一:JS判断
//判断手机横竖屏状态: window.addEventListener("onorientationchange" in window ? "orientationchange" : "resize", function() { if (window.orientation === 180 || window.orientation === 0) { alert('竖屏状态!'); } if (window.orientation === 90 || window.orientation === -90 ){ alert('横屏状态!'); } }, false);
复制
移动端的浏览器一般都支持window.orientation这个参数,通过这个参数可以判断出手机是处在横屏还是竖屏状态
屏幕方向对应的window.orientation值:
ipad,iphone: 90 或 -90 横屏
ipad,iphone: 0 或180 竖屏
Andriod:0 或180 横屏
Andriod: 90 或 -90 竖屏
方法二:CSS判断
@media screen and (orientation: portrait) { /*竖屏 css*/ } @media screen and (orientation: landscape) { /*横屏 css*/ }
复制
引用:
<!-- 竖屏 --> <link rel="stylesheet" media="all and (orientation:portrait)" href="portrait.css"> <!-- 横屏 --> <link rel="stylesheet" media="all and (orientation:landscape)" href="landscape.css">
复制
在判断是否横屏后,如互动游戏类页面,为了更好的体验则需要强制手机横屏,之后会介绍H5页面强制全屏横屏