html5仿微信手机摇一摇代码_摇一摇抽奖js代码实现
程序员文章站
2022-01-21 19:02:14
...
分享一个HTML5开发的手机端的摇一摇、整个Demo是仿微信的摇一摇功能的、当打开网页之后摇晃手机就会播放熟悉的声音、也就是会播放微信摇一摇的声音、2秒之后就会出来相应的广告信息、也就是摇动手机的结果、也是带有声音的哦、下面是整个Demo的gif效果
整个Demo主要是使用的JS代码来控制的、并包涵了一些html代码和两个mp3文件、然后就是js代码了、css样式直接写到html文件里面的、大家可以根据自己的需求更改
Html代码
<div id="hand" class="hand"><img src="images/hand.png"></div> <div id="loading" class="loading"> <span class="icon"></span> <span class="txt">正在努力的加载结果,请稍候~</span> </div> <div id="result" class="result"> <div class="con"> <div class="imgLeft"> <img src="images/logo_com01.jpg"> </div> <div class="contRight"> <p class="mainTitle">DD博客</p> <p class="subTitle">你想要的代码都能有</p> </div> </div> </div>
js监听摇晃动作
if (window.DeviceMotionEvent) { window.addEventListener(´devicemotion´, deviceMotionHandler, false); } else { alert(´抱歉,你的手机配置实在有些过不去,考虑换个新的再来试试吧´); }
deviceMotionHandler处理
function deviceMotionHandler(eventData) { var acceleration = eventData.accelerationIncludingGravity; var curTime = new Date().getTime(); if ((curTime - last_update) > 100) { var diffTime = curTime - last_update; last_update = curTime; x = acceleration.x; y = acceleration.y; z = acceleration.z; var speed = Math.abs(x y z - last_x - last_y - last_z) / diffTime * 10000; var status = document.getElementById("status"); if (speed > SHAKE_THRESHOLD) { doResult(); times ; } last_x = x; last_y = y; last_z = z; } }
function doResult() { if(times>0){ return false; } autoPlay(); document.getElementById("result").className = "result"; document.getElementById("loading").className = "loading loading-show"; document.getElementById("hand").className = "hand hand-animate"; setTimeout(function(){ autoPlayed(); }, 2500); setTimeout(function(){ times=0; document.getElementById("result").className = "result result-show"; document.getElementById("loading").className = "loading"; document.getElementById("hand").className = "hand"; }, 3000); }
html5手机摇一摇代码源代码下载链接: 微信摇一摇js代码 密码: m4w1