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

GrapesJs编辑器中如何捕获任意组件的双击(dbclick)事件

GrapesJS 组件双击事件监听方案

GrapesJS 已提供原生内置的组件双击事件,用法和你提到的component:selected、component:toggled等内置事件完全一致,可直接监听使用。

基础使用方式

编辑器初始化完成后,直接监听component:dblclick事件即可捕获所有组件的双击操作,回调参数会返回当前被双击的组件实例:

const editor = grapesjs.init({
  // 编辑器基础配置
  container: '#gjs',
  // 其余配置项...
});

// 全局监听所有组件的双击操作
editor.on('component:dblclick', (targetComponent) => {
  // 此处编写自定义业务逻辑
  console.log('当前双击组件:', targetComponent);
  console.log('组件类型:', targetComponent.get('type'));
  console.log('组件ID:', targetComponent.getId());
});

扩展场景处理

如果只需要监听特定类型组件的双击操作,可在回调中添加类型过滤逻辑:

editor.on('component:dblclick', (targetComponent) => {
  // 示例:仅响应文本组件的双击
  if (targetComponent.get('type') === 'text') {
    // 自定义逻辑,比如打开自定义富文本编辑器
    console.log('双击了文本组件');
  }
});

低版本兼容方案

如果你使用的是v0.17.x以下的老旧GrapesJS版本,内置事件不生效时可通过手动绑定画布事件的方式实现:

// 获取画布iframe的文档对象绑定双击事件
const canvasDoc = editor.Canvas.getFrameEl().contentDocument;
canvasDoc.addEventListener('dblclick', (e) => {
  // 通过点击的DOM元素获取对应的GrapesJS组件实例
  const targetComponent = editor.DomComponents.getComponentByEl(e.target);
  if (targetComponent) {
    console.log('兼容模式下获取到的双击组件:', targetComponent);
  }
});

注意事项

  • 若你自定义了组件的双击事件逻辑,注意不要阻止事件向上冒泡,否则会导致内置的component:dblclick事件无法触发。
  • 绑定事件需在编辑器初始化完成后执行,避免出现监听不生效的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 13:06:11