-
<!doctype html>
-
<html lang="en">
-
<head>
-
<meta charset="UTF-8">
-
<title>Document</title>
-
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
-
<style>
-
body,img{
-
padding:0;
-
margin:0;
-
}
-
.contain{
-
position: absolute;
-
width: 100%;
-
height: 100px;
-
bottom: 1%;
-
text-align: center;
-
}
-
#view{
-
width:100px;
-
height: 100px;
-
margin:0 auto;
-
border:1px solid #ccc;
-
position:relative;
-
line-height: 100px;
-
font-size: 20px;
-
color:red;
-
}
-
#stage{background: #ccc}
-
-
</style>
-
</head>
-
<body>
-
<div class="contain">
-
<div id="view">
-
一路顺风!
-
</div>
-
</div>
-
-
<p id="stage"></p>
-
<script type="text/javascript">
-
var view=document.getElementById('view');
-
window.addEventListener('deviceorientation',DeviceOrientationHandler,false);
-
function DeviceOrientationHandler(event){
-
var event=event || window.event;
-
var alpha = event.alpha,
-
beta = event.beta,
-
gamma = event.gamma; //gamma为Y轴旋转角度,数据类型为object
-
var stage=document.getElementById('stage');
-
var deriveW=document.body.clientWidth; //获得设备的宽度
-
var speed=(deriveW/90)*(Number(gamma)); //手机旋转时,游戏人物移动速率
-
var left=0;//初始化位置
-
var w=document.body.clientWidth/2-50;//左右两侧移动的最大距离
-
if(alpha != null || beta != null || gamma != null){
-
if( gamma > 0 ){
-
left=left+speed;
-
if(left>=w){player.style.left=w+"px";};
-
view.style.left=left+"px";
-
stage.innerHTML = "向右倾斜"+gamma+"度";
-
-
}else{
-
left=left+speed;
-
if(left<=-w){player.style.left=-w+"px";}
-
view.style.left=left+"px";
-
stage.innerHTML = "向左倾斜"+gamma+"度";
-
}
-
}
-
// alert(typeof gamma);
-
}
-
</script>
-
</body>
-
</html>
PS:附上一个介绍重力感应的博客,希望对你们有帮助: