查找当前和上一个节点悬停(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>
更多推荐
发布评论