zoukankan      html  css  js  c++  java
  • 移动端实现摇一摇并振动

    看到移动端实现摇一摇并振动功能,觉得挺实用便记录了下来。
    这个功能主要通过window.DeviceMotionEvent该事件可以监听设备的运动事件,然后通过event.accelerationIncludingGravity获取的x,y,z的位移,通过位置的变化计算设备是否在快速变化加速度以达到监听设备是否在摇一摇的效果,最后利用navigator.vibrate(s)调用触屏手机的震动功能。
    整理的代码:

    1. var shake = (function(){
    2.         var speed = 25; //摇一摇速度的临界值
    3.         var x = y = z = lastX = lastY = lastZ = 0;
    4.         var isShaking = false; //是否在动画中
    5.         return function init(callback){
    6.                 if(window.DeviceMotionEvent){
    7.                         window.addEventListener('devicemotion', function(){deviceMotionHandler(callback);}, false)
    8.                 }else{
    9.                         alert("not support mobile motion event");
    10.                 }
    11.         }
    12.         function deviceMotionHandler(callback){
    13.                 /*获取x,y,z方向的即时速度*/
    14.                 var acceleration = event.accelerationIncludingGravity;
    15.                 x = acceleration.x;y = acceleration.y;z = acceleration.z;
    16.                 if(Math.abs(x-lastX) > speed || Math.abs(y-lastY) > speed || Math.abs(z-lastZ) > speed){
    17.                         if(!isShaking){
    18.                                 //手机震动一秒
    19.                                 if (navigator.vibrate) {
    20.                                     navigator.vibrate(1000);
    21.                                 }else if (navigator.webkitVibrate) {
    22.                                     navigator.webkitVibrate(1000);
    23.                          }
    24.                 isShaking = true;
    25.                 setTimeout(function(){
    26.                         callback();
    27.                         isShaking = false;
    28.                 },2000);
    29.                         }
    30.                 }
    31.                 lastX = x;lastY = y;lastZ = z;
    32.         }
    33. }());
    34. new shake(function(){
    35. alert("您中奖了!");
    36. });
  • 相关阅读:
    运算符
    练习
    JAVA学习日报 9/23
    JAVA学习日报 8.22
    JAVA学习日报 8.21
    第一节:SpringMVC 处理请求数据【1】
    第六节:@RequestMapping 映射请求占位符 @PathVariable 注解
    第一节:REST 风格的URL地址约束
    第二节:REST风格的案例及源码分析
    (一)IOC 容器:【1】@Configuration&@Bean 给容器中注册组件
  • 原文地址:https://www.cnblogs.com/jizhijunboke/p/4993796.html
Copyright © 2011-2022 走看看