网页调用iOS触觉反馈
背景
编写了一个简单的网页应用,主要在iOS端Safari使用,希望按钮按下时能调用Taptic Engine产生轻微的震动反馈。
实现
正常情况下iOS没有提供web端的震动接口,尝试navigator.vibrate()也没有效果。
但从iOS18开始,可以通过swtich间接产生触觉反馈,同时不影响原有的button逻辑。
<div class="haptic-button">
<span>Tap me 📳</span>
<input
type="checkbox"
switch
aria-label="Tap me"
id="haptic"
/>
</div>
<style>
.haptic-button {
position: relative;
display: inline-flex;
align-items: center;
justify-content: center;
padding: 16px 32px;
border-radius: 14px;
background: #2563eb;
color: white;
font: 600 16px system-ui;
cursor: pointer;
}
.haptic-button input {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
margin: 0;
opacity: 0;
clip-path: inset(0 round 14px);
cursor: pointer;
/* Do not set appearance: none */
}
.haptic-button:active {
transform: scale(0.97);
}
.haptic-button:focus-within {
outline: 2px solid #93c5fd;
outline-offset: 3px;
}
</style>
<script>
document.querySelector("#haptic")
.addEventListener("change", () => {
console.log("Button tapped!");
// Your button action here
});
</script>

浙公网安备 33010602011771号