在 webflow 中,当我们将鼠标悬停在一个元素上时,它会显示一个蓝色边框。(参见视频)
我有兴趣知道它是如何实现的。
我已经完成了我的研究,并且可以对其实现进行基本猜测。
1 监听body上的mouseover事件
2 然后在鼠标悬停更新时使用 document.getelementfrompoint() 获取该点的元素节点
现在使用绝对定位的 div 在悬停的节点矩形上添加边框。
问题是我的猜测正确吗?
是否有我们需要检查的阈值量以避免调用 mousemove 处理程序?
最佳答案
在这里......我认为mousemove事件触发很多没有任何问题。我根本没有使用阈值(没有去抖动)。
编辑 - 在评论中回答 OP 问题 :
Why didn't you use
e.target
instead ofdocument.elementFromPoint(e.pageX, e.pageY)
?
好问题!我试过
.elementFromPoint()
首先方法,因为在您提出问题之前我不知道它。而且效果很好。我想这被称为“初学者的运气”!大声笑! -- 现在我刚刚尝试了e.target
并看到了激发您对阈值提出问题的跳跃效应。跳动效应的原因很简单。在
mousemove
生成的事件对象包含目标元素,对吧?那就是指针下的元素。一次,它是想要的元素……其次,它是我们脚本中添加的“边框 div”。它像这样不停地循环。现在使用
document.elementFromPoint(e.pageX, e.pageY)
,它始终是想要的元素,因为脚本上面的两行,我们正在删除之前的“border div”,然后查询指针下的元素。function showElement(e) {
// If there is already an appended div, remove it
let prev = document.querySelector(".border")
if(prev){
prev.remove()
}
// Get the element. If there's none, stop here to avoid errors
let elem = document.elementFromPoint(e.pageX, e.pageY)
if(!elem){return}
let elemTagname = elem.tagName.toLowerCase()
let elemRect = elem.getBoundingClientRect()
// Create a div to show the elem borders
let border = document.createElement("div")
border.classList.add("border")
border.style.top = elemRect.top + "px"
border.style.left = elemRect.left + "px"
border.style.width = elemRect.width + "px"
border.style.height = elemRect.height + "px"
// Create a span to show the tag name
let tag = document.createElement("span")
tag.classList.add("tag")
tag.innerText = elemTagname
// Append!
border.append(tag)
document.documentElement.append(border)
}
// Mousemove handler
document.documentElement.addEventListener("mousemove", showElement)
div{
height: 300px;
}
.border{
border: 1px solid blue;
position: absolute;
top: 0;
left: 0;
width: 0;
height: 0;
}
.tag{
background: lightgrey;
color: blue;
font-family: arial;
margin-left: 0.3em;
padding: 0 0.3em;
}
<div>
<h1>Header</h1>
<p>Paragraph</p>
<ul>
<li>List item</li>
<li>List item</li>
<li>List item</li>
</ul>
</div>
关于javascript - 在 webflow 中为悬停时添加小部件的边框实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66845331/