移动端的摇一摇实现效果
时间:5年前 阅读:4746
摇一摇的原理非常简单,检测到手机的重力加速忽然有比较大的变化幅度即可。摇一摇时,元素颜色发生变化
实例代码如下:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style type="text/css"> #box{ width: 100px; height: 100px; background: pink; margin: 30px auto 0; text-align: center; transition: 1s; } </style> </head> <body> <div id="box">摇一摇变颜色</div> </body> <script type="text/javascript"> let oBox = document.getElementById('box'); let colorArr = ['orange','lightblue','lightgreen','pink','lightyellow'] let lastX,lastY,lastZ let index = 0 window.addEventListener('devicemotion',(e)=>{ requestAnimationFrame(()=>{ let {x,y,z} = e.accelerationIncludingGravity let nowRange = Math.abs(lastX -x) + Math.abs(lastY - y) + Math.abs(lastZ - z) if(nowRange > 80){ index = (index+1)%colorArr.length oBox.style.background = colorArr[index] } lastX = x lastY = y lastZ = z }) }) </script> </html>
效果图片:
本站声明:网站内容来源于网络,如有侵权,请联系我们https://www.qiquanji.com,我们将及时处理。
微信扫码关注
更新实时通知
网友评论