检测手机横竖屏切换

我们做移动端项目的时候,为了更好的完善用户体会,经常会需要处理好手机横竖屏时候的效果,下面看一下通过代码如何判断手机是否是横竖屏,两种方式:

一、第一种方式:

<style type="text/css">
body,
html {
margin: 0;
height: 100%;
position: relative;
overflow: hidden;
}
#box {
width: 100%;
height: 100%;
font-size: 20px;
position: relative;
}
#div {
width: 100px;
height: 100px;
background: red;
}
#pop {
display: none;
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
background: #000;
color: #fff;
line-height: 200px;
font-size: 30px;
text-align: center;
}
</style>
</head>
<body>
<div id="box">
请保持竖屏观看哟
<div id="div"></div>
</div>
<div id="pop">请不要横屏浏览页面</div>
<script type="text/javascript">
setChange();
window.addEventListener('orientationchange', function(e)
{
setChange()
});
function setChange(){
var pop = document.querySelector('#pop');
if(window.orientation == 90 || window.orientation == -90)
{
pop.style.display = "block";
} else {
pop.style.display = "none";
}
}
</script>

二、第二种方式
<style type="text/css">
body,
html {
margin: 0;
height: 100%;
position: relative;
overflow: hidden;
}
#box {
position: absolute;
left: 50%;
top: 50%;
font-size: 20px;
position: relative;
}
#div {
width: 100px;
height: 100px;
background: red;
}
</style>
</head>
<body>
<div id="box">
请保持竖屏观看哟
<div id="div"></div>
</div>
<div id="pop">请不要横屏浏览页面</div>
<script type="text/javascript" src="m.Tween.js"></script>
<script type="text/javascript">
setStyle()
setChange();
window.addEventListener('orientationchange', function(e)
{
setChange();
});
function setStyle(){
var box = document.querySelector('#box');
var w = window.screen.width;
var h = window.screen.height;
box.style.width = w + "px";
box.style.height = h + "px";
box.style.margin = -h/2 + "px 0 0 "+(-w/2)+"px";
}
function setChange(){
var box = document.querySelector('#box');
if(window.orientation == 90 || window.orientation == -90)
{
css(box,"rotate",90);
} else {
css(box,"rotate",0);
}
}
</script>

分享技术,分享快乐!
posted @ 2017-02-20 17:57  win.w  阅读(343)  评论(0编辑  收藏  举报