如何不将(鼠标悬停)传递给 children,但保持 parent 占用的整个 space 的功能可用?

How to not pass (mouseover) to children, but keep the function available on the whole space that the parent takes up?

我有一个动态生成的列表,其中包含应该在 mouseover.

上执行操作的复杂组件

因为我使用 Angular,所以我尝试在组件的最高 parent 元素上使用 (mouseover)="onhover($event)"(mouseout)="onhover($event) 来构建它,然后获取它并进行路由从那里到应该改变的不同组件。

<div class="my-list_element" id="{{'my-list_element' + i}}" (mouseover)="onhover($event)" (mouseout)="onhover($event)" >

然后 Typescript 代码通常具有捕获事件的功能:

onhover(event: Event){
    let id = (event.target as HTMLInputElement).id;
    console.log(id.toString());
  }

在测试它是否有效时我注意到,如果我不直接将鼠标悬停在组件的 parent 上,children 的 ID 会记录在控制台中,这不会使静态路由到应该更改的元素。

是否可以保持mouseover/mouseout在整个组件上可用,但仍然只获取整个组件中最高parent的id?

尝试event.stopPropagation()。这将阻止事件冒泡。 在这里阅读更多: https://www.w3schools.com/jsref/event_stoppropagation.asp

您可以参考 event.currentTarget 而不是 event.target:

The currentTarget read-only property of the Event interface [...] always refers to the element to which the event handler has been attached, as opposed to Event.target, which identifies the element on which the event occurred and which may be its descendant.

请注意,在下面的代码片段中,无论触发事件的元素是什么,currentTarget 始终是包含 <li> 的元素:

function doStuff(e) {
  console.clear();
  console.log(`target: ${e.target.className}`); // div-child
  console.log(`currentTarget: ${e.currentTarget.className}`); // li-parent
}
ul {
  list-style: none;
  margin: 0;
  padding: 1rem;
  background: tomato;
}

li {
  padding: 0.25rem;
  background: bisque;
}

li div {
  background: white;
  margin: 0.5rem;
  padding: 0.5rem;
}
<ul>
  <li class="li-parent" onmouseover="doStuff(event)">
    <div class="div-child">child 1</div>
    <div class="div-child">child 2</div>
  </li>
</ul>