You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Alpine.js中触发@touchstart时阻止@click事件?

问题分析与解决方案

首先先明确你的场景:
你用Alpine.js写了这段链接代码:

<a href="#home" @click="myFunction(event)" @touchstart.prevent="myFunction(event)"> My Link </a>

对应的事件处理函数:

function myFunction(ev) {
  console.log(ev.type + ' -> myfunc');
}

你期望控制台只输出touchstart -> myfunc,但在Firefox开发者工具测试时,会同时触发click事件打出两条日志;而在Chromium系浏览器的开发者工具里,表现完全符合预期。你还试过@touchstart.stop,但也没效果。

原因解释

这不是你的代码操作有误,大概率是Firefox开发者工具在模拟触摸事件时的行为bug。

在真实触摸设备环境中,浏览器处理完触摸事件后,会有300ms延迟判断用户是否要执行双击;如果在touchstart里调用了preventDefault(),正常会阻止后续的click事件触发。但Firefox的触摸模拟器可能没完全还原这个原生逻辑,导致即使加了.prevent,还是会触发click。

验证与可选兜底方案

  1. 真实设备测试:你可以拿手机这类真实触摸设备打开Firefox测试,应该会符合预期——只触发touchstart事件。
  2. 开发环境兜底逻辑:如果想在开发时也避免这个问题,可以给事件处理函数加个额外判断,手动拦截click:
function myFunction(ev) {
  console.log(ev.type + ' -> myfunc');
  
  if (ev.type === 'touchstart') {
    ev.preventDefault();
    // 标记已触发触摸事件
    ev.target.dataset.touched = 'true';
  } else if (ev.target.dataset.touched === 'true') {
    // 阻止click的默认行为与逻辑执行
    ev.preventDefault();
    delete ev.target.dataset.touched;
    return;
  }
}

总结

你的代码逻辑本身是正确的,问题出在Firefox开发者工具的触摸事件模拟机制上,属于工具的小问题,不会影响真实用户的使用体验。

内容的提问来源于stack exchange,提问作者umphy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 11:17:59