如何在鼠标悬停时检测 div 内的所有链接

How to detect all links within a div, on mouseover

在 Svelte 应用程序中,我试图检测用户何时将鼠标悬停在 link 上,位于 div 内。我已经向 div 添加了一个 mouseover 事件侦听器,并且正在检查该元素是否是 link,但这太简单了:它没有检测到 link包含 HTML 个标签。

示例代码,还有 available as REPL:

<script>
    import { onMount } from 'svelte';
    
    let container;
    
    onMount(() => {
    container.addEventListener('mouseover', async (event) => {
            if (event.target.tagName !== 'A') return;
            console.log(event.target.attributes['href'].value);
        });
    });
</script>

<div bind:this={container}>
    <a href="https://www.example.com">Hello World</a>
    <a href="https://www.example.com"><strong>Hello World</strong></a>
</div>

问题是第二个 link:将鼠标悬停在它上面时,目标是 strong 标签,而不是 a 标签。那么,我如何才能可靠地检测容器 div 中的所有 link,而不必为每个个体添加事件侦听器 link?

从目标中,使用 .closest('a') 导航到封闭的 <a> 元素(如果有)。 (如果事件被分派到的元素是 <a>,它将被返回。)

container.addEventListener('mouseover', (event) => {
    const a = event.target.closest('a');
    if (a) console.log(a.href);
});

container.addEventListener('mouseover', (event) => {
  const a = event.target.closest('a');
  if (a) console.log(a.href);
});
<div id="container">
  <a href="https://www.example.com">Hello World</a>
  <a href="https://www.example.com"><strong>Hello World</strong></a>
</div>

除了将容器绑定到变量并在 onMount 中设置侦听器之外,您还可以在 Svelte 中直接在元素上设置它,如下所示

<script>        
    function handleMouseover() {
        const a = event.target.closest('a')
        if(a) console.log(a.href);
    };
</script>

<div on:mouseover={handleMouseover}>
    <a href="/path">Hello World</a>
    <a href="https://www.example.com"><strong>Hello World</strong></a>
</div>