相信这个demo有很多人写过的,简单的不说了。本例的demo非常简短,还配了个漂亮了图片(图是在某图库网下载的,只用于开发技术学习,禁用于商业);没什么好介绍的,可以直接复制代码使用,下面贴个效果图
下面贴代码
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
<script type="text/javascript" src="http://xxiaoyuan.top/jquery-1.9.1.js" ></script>
<style type="text/css">
*{
padding: 0;
margin: 0 auto;
}
body{
background-color: #333;
}
.compass{
position: relative;
}
.compass img{
width: 100%;
}
.compass .pa{
position: absolute;
top: 0;
left: 0;
z-index: -1;
}
.compass .pa_p {
color: #e46f19;
font-size: 40px;
top: 100%;
left: 50%;
transform: translateX(-50%);
z-index: 1;
}
.box{
width: 90%;
margin: 20% auto;
}
</style>
</head>
<body>
<div class="box">
<div class="compass">
<img src="./img/a0.png">
<img class="pa" src="./img/a2.png" id="compass">
<img class="pa" src="./img/a3.png">
<div class="pa pa_p"><span id="alpha"></span>°</div>
</div>
</div>
</body>
<script>
var alpha = ""
var ua = navigator.userAgent.toLowerCase();
if(/android/.test(ua)) {
window.addEventListener('deviceorientationabsolute', DeviceOrientationHandler, false);
function DeviceOrientationHandler(event) {
document.getElementById("alpha").innerHTML = Math.round(360 - event.alpha);
$('#compass').css('transform','rotate(-'+Math.round(360 - event.alpha)+'deg)')
}
} else {
window.addEventListener('deviceorientation', DeviceOrientationHandler, false);
function DeviceOrientationHandler(event) {
document.getElementById("alpha").innerHTML = event.webkitCompassHeading;
$('#compass').css('transform','rotate(-'+event.webkitCompassHeading+'deg)')
}
}
</script>
</html>