【问题标题】:How to detect whether device has a vibrator?如何检测设备是否有振动器?
【发布时间】:2014-07-14 16:05:56
【问题描述】:

使用navigator.vibrate 可以让智能手机和平板电脑振动。但是,该功能也可以在桌面浏览器上使用,因此它的存在对于检测振动电机是否实际可用是没有用的。

当然,我可以检查设备是否正在运行移动操作系统以获得适当的近似值,但是有没有适当的方法来检测振动是否实际可用?

原因:我在游戏中使用了振动,并为此添加了一个开/关按钮。在台式 PC 上显示此按钮是没有意义的。

【问题讨论】:

  • @ZougenMoriver 鉴于这是一个决定性的答复,您应该用相关的引号写一个答案。

标签: javascript html vibration


【解决方案1】:

不幸的是,听起来你不能:

显然这是故意的,以避免暴露可访问性 设置(被视为敏感),以允许 UA 提供 后备,也可能成为指纹识别的障碍。

来自http://github.com/Modernizr/Modernizr/issues/1217

The spec itself 说:

如果模式是一个空列表,或者如果设备无法振动, 然后返回 true 并终止这些步骤。

【讨论】:

    【解决方案2】:

    似乎无法检测到设备是否真的会以某种方式振动,所以当我遇到类似问题时,我只是在操作系统似乎不是移动设备时使用回退来发出声音:

    var navigatorTest = (function(ua){
      return function(){
        for(var i=0; i<arguments.length; ++i) {
          if(ua.indexOf(arguments[i]) >= 0)
            return true;
        }
        return false;
      };
    })(navigator.userAgent);
    
    var bleep = ((
      (navigatorTest("iPad", "iPod", "iPhone", "Android") || !navigatorTest("Macintosh", "Windows", "X11", "Linux"))
      && (navigator.vibrate || navigator.webkitVibrate || navigator.mozVibrate || navigator.msVibrate)
    ) || (
      function(ctx){
        return function(len){
            var osc = ctx.createOscillator();
            osc.connect(ctx.destination);
            osc.start();
            setTimeout(function(){
                osc.stop();
            }, len);
        };
      }
    )(
      window.AudioContext ? new AudioContext() : new webkitAudioContext()
    )).bind(navigator, 300);  // Vibration/bleep time
    

    虽然这不是你的意思(不是特征检测),但它提供了一个公平的后备。

    【讨论】:

      猜你喜欢
      • 2011-10-11
      • 1970-01-01
      • 2011-09-08
      • 1970-01-01
      • 1970-01-01
      • 2015-07-19
      • 1970-01-01
      • 1970-01-01
      • 2017-07-12
      相关资源
      最近更新 更多