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

如何实现自定义元素从mousedown到mouseup/mouseleave持续执行函数的FireFox兼容

问题根因

Firefox 在鼠标按下时会默认触发文本选中、元素拖放逻辑,这会中断元素自身绑定的事件流,导致mouseup、mouseleave事件无法按预期触发,这是该问题仅在Firefox出现的核心原因。

修复方案

  • 在mousedown回调中添加event.preventDefault(),阻止Firefox的默认拖放/选中文本行为,避免事件流被中断
  • 将mouseup、mouseleave事件绑定到全局window对象上,确保无论鼠标在页面哪个位置松开、或者移出元素,都能正确终止函数执行
  • 修正代码笔误:将setTimeOut改为标准写法setTimeout
  • 补充自定义元素的disconnectedCallback生命周期逻辑,移除全局事件监听避免内存泄漏

修改后可兼容Firefox的代码

// attaching event listeners in connectedCallback
connectedCallback() {
  /*
    Some other code before...
  */
  this.addEventListener('mousedown', this._onMouseDown)
  this.addEventListener('mouseenter', this._setMouseOnTrue)
  // 事件绑定到window,保证全局触发
  window.addEventListener('mouseup', this._setMouseOnFalse)
  window.addEventListener('mouseleave', this._setMouseOnFalse)
}

_setMouseOnTrue(event) { this._mouseOn = true}
_setMouseOnFalse(event) { this._mouseOn = false }
_onMouseDown(event) {
  if (event.button === 0) {
    // 阻止Firefox默认行为
    event.preventDefault()
    this._setMouseOnTrue(event)
    this.func()
  }
}

func() {
  if (this._mouseOn) {
    this._privateFunc()
    // 修正大小写错误
    setTimeout(this.func.bind(this), time)
  }
}

// 移除事件监听避免内存泄漏
disconnectedCallback() {
  window.removeEventListener('mouseup', this._setMouseOnFalse)
  window.removeEventListener('mouseleave', this._setMouseOnFalse)
  this.removeEventListener('mousedown', this._onMouseDown)
  this.removeEventListener('mouseenter', this._setMouseOnTrue)
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 10:45:02