使用设备加速计的移动网络浏览器的自定义“摇动”事件 JavaScript 插件。
npm install shake.js
bower install shake.js
git clone https://github.com/alexgibson/shake.js
您的网络浏览器必须支持devicemotion
事件才能使该插件正常工作。 Shake.js 使用内置功能检测来确定它是否可以在您的 Web 浏览器中运行。它将在不支持的浏览器上静默终止。
http://w3c.github.io/deviceorientation/spec-source-orientation.html
对于使用 NPM 的 CommonJS:
var Shake = require('shake.js');
对于 AMD 模块:
define(['./shake'], function(Shake) {
// ...
});
在浏览器中:
<script src="shake.js"></script>
接下来,创建一个新的 Shake 实例:
var myShakeEvent = new Shake({
threshold: 15, // optional shake strength threshold
timeout: 1000 // optional, determines the frequency of event generation
});
开始监听设备运动:
myShakeEvent.start();
使用回调在window
上注册shake
事件侦听器:
window.addEventListener('shake', shakeEventDidOccur, false);
//function to call when shake occurs
function shakeEventDidOccur () {
//put your own code here etc.
alert('shake!');
}
您可以停止监听震动事件,如下所示:
window.removeEventListener('shake', shakeEventDidOccur, false);
要停止监听设备运动,您可以调用:
myShakeEvent.stop();