查找当前和上一个节点悬停

时间:2016-09-26 15:49:38

标签: javascript frontend

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

由于

3 个答案:

答案 0 :(得分:1)

当鼠标离开时,您需要存储该元素,并在鼠标输入时检查它是什么。例如:

var previous;

$('div').on('mouseleave',function(event){
    previous = $(this);
});

$('div').on("mouseenter", function(event){
    console.log($(this).text(), previous.text());
})

jsFiddle

答案 1 :(得分:0)

纯JavaScript

var previouslyHovered
var currentlyHovered
var previousBox = document.querySelector('.previouslyHovered')
var currentBox = document.querySelector('.currentlyHovered')

var items = document.querySelectorAll('li')

items.forEach(item => item.addEventListener('mouseover', function() {
  previouslyHovered = currentlyHovered
  previousBox.textContent = previouslyHovered
    ?previouslyHovered.textContent
    :previousBox.textContent
  
  currentlyHovered = this
  currentBox.textContent = currentlyHovered.textContent
}))
<ul>
  <li>item 1</li>
  <li>item 2</li>
  <li>item 3</li>
</ul>
<div>previous
<span class="previouslyHovered">n/a</span>
</div>
<div>current
<span class="currentlyHovered">n/a</span>
</div>

答案 2 :(得分:0)

将其存储在全局变量中:

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>