查找当前和上一个节点悬停(Find current and previous node hovered)

编程入门 行业动态 更新时间:2024-10-28 05:16:47
查找当前和上一个节点悬停(Find current and previous node hovered)

我有一个包含带链接的孩子的HTML列表。 我想找到当前悬停的元素,以及之前悬停的元素。 (不是当前徘徊的兄弟之前的兄弟姐妹,只是直到当前徘徊的物品)。

谢谢

I have an html list that contains children with links. I want to find the current element that is hovered, and also the previously hovered one. (Not the previous sibling of the one currently hovered, just the item that was hovered until the current).

Thanks

最满意答案

将其存储在全局变量中:

var hoveredElement; // We'll store our "previous" data here

// Add a hover listener to the UL, then delegate to the anchors 
document.querySelector('ul').addEventListener('mouseover', function(e) {
  if (e.target && e.target.matches('a')) {
    
    // If we have a previous hovered element, add it
    if (hoveredElement) {
      document.querySelector('.previous').textContent = hoveredElement
    }

    // Set the current hovered and the "new" last hovered elements to the currently hovered element
    document.querySelector('.current').textContent = hoveredElement = e.target.textContent
  }
}); 
  
<ul>
  <li>
    <a href="#">Item 1</a>
  </li>
  <li>
    <a href="#">Item 2</a>
  </li>
  <li>
    <a href="#">Item 3</a>
  </li>
</ul>
<hr />
<p>Current: <span class="current"></span></p>
<p>Previous: <span class="previous"></span></p> 
  
 

Store it in a global variable:

var hoveredElement; // We'll store our "previous" data here

// Add a hover listener to the UL, then delegate to the anchors 
document.querySelector('ul').addEventListener('mouseover', function(e) {
  if (e.target && e.target.matches('a')) {
    
    // If we have a previous hovered element, add it
    if (hoveredElement) {
      document.querySelector('.previous').textContent = hoveredElement
    }

    // Set the current hovered and the "new" last hovered elements to the currently hovered element
    document.querySelector('.current').textContent = hoveredElement = e.target.textContent
  }
}); 
  
<ul>
  <li>
    <a href="#">Item 1</a>
  </li>
  <li>
    <a href="#">Item 2</a>
  </li>
  <li>
    <a href="#">Item 3</a>
  </li>
</ul>
<hr />
<p>Current: <span class="current"></span></p>
<p>Previous: <span class="previous"></span></p> 
  
 

更多推荐

本文发布于:2023-07-16 18:29:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1132392.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:节点   Find   current   hovered   node

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!