有没有一种简单的方法来检测容器中最接近鼠标点击坐标的子元素?在这种情况下,容器是一个 div
例如:
<div style="white-space: pre-wrap">
<span>E1</span>
<span>\n</span>
<span>\n</span>
<span>E4</span>
<span>E5</span>
</div>
在上述情况下,我想确定与 div 中发生点击的位置最接近的顶部/左侧坐标的范围。由于换行,跨度没有完全覆盖 div
在我的点击事件中,我可以通过 e.clientY 访问顶部/左侧;
但是,我在遍历跨度以检测哪个跨度最接近 div 内的点击坐标时遇到了一些困难。
点击处理程序:
function(e){
var yop = e.clientY;
}
最佳答案
以下是一些可能对 document.elementFromPoint
有用的链接:
来自 MDN 链接上的摘要:
Returns the element from the document whose elementFromPoint method is being called which is the topmost element which lies under the given point. To get an element, specify the point via coordinates, in CSS pixels, relative to the upper-left-most point in the window or frame containing the document.
http://www.quirksmode.org/dom/w3c_cssom.html
https://developer.mozilla.org/en-US/docs/DOM/document.elementFromPoint
简而言之,它在 x, y
坐标处将 pin 向下放置在 z-index 堆栈中,并返回它命中的第一个元素。 super 有用,尽管根据 Quirksmode 页面,它的支持是有限的。
关于javascript - 查找最接近点击坐标的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16070746/