javascript - 使用 Javascript 在 iOS Safari 中检测震动?

标签 javascript cocoa-touch ios mobile-safari

我如何利用新的 MobileSafari 设备运动 API 来捕捉“摇动”事件?

最佳答案

查看这篇很棒的博文:http://www.jeffreyharrell.com/blog/2010/11/creating-a-shake-event-in-mobile-safari/

这说明了这个例子:

if (typeof window.DeviceMotionEvent != 'undefined') {
    // Shake sensitivity (a lower number is more)
    var sensitivity = 20;

    // Position variables
    var x1 = 0, y1 = 0, z1 = 0, x2 = 0, y2 = 0, z2 = 0;

    // Listen to motion events and update the position
    window.addEventListener('devicemotion', function (e) {
        x1 = e.accelerationIncludingGravity.x;
        y1 = e.accelerationIncludingGravity.y;
        z1 = e.accelerationIncludingGravity.z;
    }, false);

    // Periodically check the position and fire
    // if the change is greater than the sensitivity
    setInterval(function () {
        var change = Math.abs(x1-x2+y1-y2+z1-z2);

        if (change > sensitivity) {
            alert('Shake!');
        }

        // Update new position
        x2 = x1;
        y2 = y1;
        z2 = z1;
    }, 150);
}

关于javascript - 使用 Javascript 在 iOS Safari 中检测震动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4475219/

相关文章:

javascript - jquery slide div 通过改变边距

ios - 如何让多个音频流在 iOS 中重叠播放?

ios - 如何使用 Storyboard 设置包装文本 UILabel Xcode

ios - 另一个“NSInvalidArgumentException:无法识别的选择器发送到实例”帖子

ios - UICollectionview 滚动时向服务器发送请求?

javascript - 将表单数据转换为 JSON 字符串

javascript - FileReader 无法在 iOS 8 上运行

javascript - 在three.js中计算边界框水平边缘的屏幕坐标

iphone - 如何避免将一个单词拆分为两个 UITextView

ios - UIButton _setTitleFrozen 崩溃