使用裝置加速計的行動網路瀏覽器的自訂「搖動」事件 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();