如何在您的网站中使用振动 API

2025-05-27

如何在您的网站中使用振动 API

大家好👋

在本文中,我们将了解如何Vibration API在我们的网站中使用。

我们可以使用Vibration API为使用网站的用户提供触觉或振动反馈。

大多数现代移动设备都包含振动硬件,这使得软件代码可以通过震动设备来向用户提供物理反馈。因此,此 API 仅适用于移动设备,并且目标也是移动设备。

如果存在振动硬件,则Vibration API允许网络应用程序访问该硬件。

实施

让我们探索一下 API。

我们可以从浏览器的对象访问 API window.navigator

检查Vibration API支持

检查 API 支持始终是一个好主意。



if (Boolean(window.navigator.vibrate)) {
    // It Supports
    ...
}


Enter fullscreen mode Exit fullscreen mode
  • vibrate是一种负责振动的方法。
  • 它需要一个参数。

参数是一个数字或一系列振动的数字数组。这些数字被视为milliseconds

如果该方法由于参数无效而无法振动,则返回,false否则返回true

单次振动📳

对于单次振动,我们可以直接传递单个数字或以数组形式传递。



// Will vibrate the device for 500ms
window.navigator.vibrate(500);

// Same as the above line
window.navigator.vibrate([500]);


Enter fullscreen mode Exit fullscreen mode

图案振动📳📳📳

为了使设备按照某种模式振动,我们可以传递一个数字数组。

偶数索引号负责振动,而奇数索引号将在下一次振动之前延迟那么多毫秒。



// Vibrate for 500ms, Wait for 200ms, Vibrate for 800ms
window.navigator.vibrate([500, 200, 800]);


Enter fullscreen mode Exit fullscreen mode

消除振动

要取消正在进行的振动模式,我们需要0向方法传递一个空数组或一个包含全零的数组vibrate



window.navigator.vibrate(0);
window.navigator.vibrate([])


Enter fullscreen mode Exit fullscreen mode

有趣的例子✨

以摩尔斯电码振动SOS



window.navigator.vibrate([
    100,30,100,30,100,30,
    200,30,200,30,200,30,
    100,30,100,30,100
]);


Enter fullscreen mode Exit fullscreen mode

*Working only on Chrome Android

示例代码|实时链接


最初发表于blog.bibekkakati.me


感谢您的阅读🙏

如果您喜欢这篇文章或觉得它有帮助,请点赞👍

欢迎随时联系👋

Twitter | Instagram | LinkedIn


如果你喜欢我的作品并想支持它,可以在这里留言。我会非常感激。



文章来源:https://dev.to/bibekkakati/how-to-use-vibration-api-in-your-website-4dp4
PREV
Typescript 与 React 结合使用的初学者指南
NEXT
逃离教程地狱的权威指南