← 中文资源

简体中文版本

composedPath 找到事件的真实目标

在 shadow root 外监听时,event.target 只会是宿主元素;composedPath() 返回真实的内部链路,而 closed 模式会把路径在边界处截断,外部只能看到宿主本身。

阅读英文原文

机制说明

open shadow root 内按钮的 click 冒泡到宿主监听器时,event.target 被改写为宿主——重定向把内部节点对外隐藏。composedPath()[0] 返回按钮本身,传播路径的真实首节点。

后半段挂 closed shadow root:composedPath 仍有返回,但路径在边界截断——打印的首节点是 closed-card 宿主,内部元素对外部监听器永远不可见。

注意事项

  • 重定向对 shadow 树之外的任何监听器都生效。
  • closed 模式无法绕过:composedPath 同样尊重边界。

核心语句

console.log('real target:', event.composedPath()[0].tagName);

代码示例

// Shadow DOM retargeting: listeners outside the shadow root see the host as event.target
const host = document.createElement('user-card');
const shadow = host.attachShadow({ mode: 'open' });
const button = document.createElement('button');
button.textContent = 'Save';
shadow.append(button);
document.body.append(host);

host.addEventListener('click', (event) => {
  // From outside, event.target is the host element
  console.log('target:', event.target.tagName);
  // composedPath() hands back the real inner chain
  console.log('real target:', event.composedPath()[0].tagName);
  console.log('path length:', event.composedPath().length);
});

button.click();

// mode:'closed' truncates the path for outsiders: the first node is the host itself
const closedHost = document.createElement('closed-card');
const closedShadow = closedHost.attachShadow({ mode: 'closed' });
const inner = document.createElement('button');
closedShadow.append(inner);
document.body.append(closedHost);

closedHost.addEventListener('click', (event) => {
  console.log('closed first node:', event.composedPath()[0].tagName);
});

inner.click();