移动端h5实现摇一摇抽奖
生活随笔
收集整理的這篇文章主要介紹了
移动端h5实现摇一摇抽奖
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
話不多說,老規(guī)矩,先上預覽:blogai.cn
由于新?lián)Q了服務器,還在備案審核中,所以,前面的預覽地址都打不開了,等過幾天就好了。
?
首先,我們先用css實現(xiàn)一個搖動的手機,能很好地帶入用戶。
實現(xiàn)如下:
<style rel="stylesheet" type="text/css">*{box-sizing: border-box;}body{background: cornflowerblue;}.phone{width: 400px;height: 800px;background: #ffffff;border: 1.5px solid #000000;text-align: center;position: absolute;top: 0;bottom: 0;left: 0;right: 0;margin:auto;border-radius: 60px;animation: shake 2s ease infinite;}.screen{background: #000000;width: 90%;height: 72%;margin: 0 auto;transform: translateY(18%);position: center;}.btn{border: 1.5px solid #000000;border-radius: 50%;width: 80px;height: 80px;bottom:2%;left: 50%;transform: translateX(-50%);position: absolute;}.receiver{position: absolute;background: black;width: 25%;height: 10px;top:6%;left: 40%;border-radius: 5px;border: 1px solid #ffffff;}.circle{width: 15px;height: 15px;background: black;border-radius: 50%;left: -40%;position: absolute;transform: translateY(-40%);}.show{font-size: 40px;font-weight: bold;line-height: 560px;text-align: center;color:#ffffff;}.circle2{width: 10px;height: 10px;background: black;border-radius: 50%;left: 50%;top:3%;position: absolute;}@keyframes shake {from{transform: rotate(0deg);}4%{transform: rotate(10deg);}12.5%{transform: rotate(-10deg);}21%{transform: rotate(10deg);}29%{transform: rotate(-10deg);}37.5%{transform: rotate(10deg);}46%{transform: rotate(-10deg);}50%,to{transform: rotate(0deg);}}</style>html:
<div class="phone"><div class="screen"><span id='show' class="show">搖一搖 有好禮</span></div><div class="btn"></div><div class="receiver"><span class="circle"></span></div><div class="circle2"></div></div>這樣就實現(xiàn)了一個搖動的手機,如圖所示:
要實現(xiàn)搖動,需要監(jiān)聽手機的搖動變化,可以使用html中的devicemotion實現(xiàn)。
首先要做的是查看設備是否支持運動傳感事件。
if (window.DeviceMotionEvent) {window.addEventListener('devicemotion', shake) //devicemotion:獲取設備的運動狀態(tài)} else {document.getElementById('show').innerHTML = '換部手機試試~'}然后設置一個閾值,當搖動大于閾值時,觸發(fā)中獎函數(shù)。草率地計算下,具體實現(xiàn)等后續(xù)吧。。。
let max = 5000; //晃動最大值,閾值let x, y, z, lastX, lastY, lastZ = 0; //初始化x,y,z軸的加速度let lastTime, currentTime;lastTime = new Date().getTime();function shake(e) {let a = e.accelerationIncludingGravity; //獲取加速度x = a.x; //x,y,z軸上的加速度y = a.y;z = a.z;currentTime = new Date().getTime();//console.log(currentTime-lastTime);兩次時間差if ((currentTime - lastTime) > 1000) {//這行的大致意思就是搖的越快,speed值越高var speed_ = Math.abs(x + y + z - lastX - lastY - lastZ) / (currentTime - lastTime) * 1000;document.getElementById('show').innerHTML = speed_.toFixed(2);lastTime = currentTime;lastX = x;lastY = y;lastZ = z;}if (speed_>max){window.removeEventListener('devicemotion',shake);document.getElementById('show').innerHTML = '來了老弟!'}}好了,最后,預覽地址:zjrzjr.cn
總結
以上是生活随笔為你收集整理的移动端h5实现摇一摇抽奖的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ANTLR使用访问器遍历语法树
- 下一篇: AmazeUI 图片轮播模块FlexSl