博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
网页检测摇一摇
阅读量:7027 次
发布时间:2019-06-28

本文共 2089 字,大约阅读时间需要 6 分钟。

hot3.png

var Shaker = function(f){    // 摇一摇: 检测到3次摇动算一次摇一摇, 摇动后调用处理函数, 不再检测摇动    // f 摇动后的回调    this.callback = f;    this.status = 0;    // 0: 侦听未开始 1: 侦听开始     this.speed = 15;    this.lastX = this.lastY = this.lastZ = 0;    this.num = 0;       // 检测触发次数    this.minNum = 3;    // 最小检测触发次数    this.beginSecond = 0;   // 开始检测的秒数    this.maxSecond = 3;     // 最大间隔秒数        this.handlerWrap = function(){};}Shaker.prototype.listen = function(){    // 侦听摇动    var that = this;    if (this.status == 0 && window.DeviceMotionEvent) {        this.status = 1;        this.handlerWrap = function(event){            that.handler(event)        }        window.addEventListener('devicemotion', this.handlerWrap, false);    }}Shaker.prototype.release = function(){    // 停止侦听    if(this.status == 1){        if (window.DeviceMotionEvent) {            window.removeEventListener('devicemotion', this.handlerWrap);        }        this.status = 0;        this.num = 0;    }}Shaker.prototype.reset = function(){    // 重置检测    if(this.status == 1){        this.num = 0;    }}Shaker.prototype.handler = function(event){    // 传感器事件处理    if(this.status == 1){        var acceleration =event.accelerationIncludingGravity;        var x = acceleration.x;        var y = acceleration.y;        var z = acceleration.z;        if( Math.abs(x-this.lastX) > this.speed ||             Math.abs(y-this.lastY) > this.speed ||             Math.abs(z-this.lastZ) > this.speed )         {            if(this.num == 0){                this.beginSecond = Date.parse(new Date()) / 1000            }            this.num += 1;        }        this.lastX = x;        this.lastY = y;        this.lastZ = z;        if(this.num >= this.minNum){            var now = Date.parse(new Date()) / 1000;            if(now - this.beginSecond <= this.maxSecond){                this.release();                if(this.callback){                    this.callback();                }            }            this.reset();        }    }}

用法:

    var s = new Shaker(function(){ /*摇动后的回调*/ });

    s.listen();

转载于:https://my.oschina.net/airxiechao/blog/602287

你可能感兴趣的文章
centos7 yum搭建lamp
查看>>
Oracle 热备份
查看>>
mairadb数据库同步(从服务器同步主服务数据)
查看>>
CFNetwork framework
查看>>
DevExpress GridControl 复合表头/表头分层设计.
查看>>
Flex布局知识点
查看>>
SIGABRT错误的解决办法
查看>>
Guava cache功能整理
查看>>
lsscsi命令详解
查看>>
Elementary Methods in Number Theory Exercise 1.2.25
查看>>
记:安卓上的行内元素清除浮动失效
查看>>
面试题
查看>>
python之装饰器
查看>>
TOMCAT配置SSL认证为HTTPS协议服务
查看>>
空间谱专题08:相位模糊
查看>>
infoepo sql用法整理
查看>>
Codeforces Round #353 (Div. 2)
查看>>
20145234黄斐《Java程序设计》第六周学习总结
查看>>
js数据类型?
查看>>
使用BTRACE定位系统中慢的问题
查看>>