javascript - 查找最接近点击坐标的元素

标签 javascript jquery html dom

有没有一种简单的方法来检测容器中最接近鼠标点击坐标的子元素?在这种情况下,容器是一个 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/

相关文章:

javascript - 如何根据N :N relationship 检索SOAP中的相关记录

jquery - 使用 jQuery 更改文档加载时的 <span> 文本

javascript - 折叠/展开所有菜单项。 - HTML/JS/CSS/ Bootstrap 3

javascript - 在rails app + jquery 中生成的链接错误地定向到本地主机

javascript - 将 JavaScript for 循环集成到自定义函数中

javascript - 通过查找类和选中的复选框类型来获取自定义属性值的数组

html - 是否可以在已经旋转的 X 中旋转 X

php - mysqli_real_escape_string 不插入数据库

javascript - 使用对象计算变化 - javascript

javascript - YouTube JS API : play by random time point on button click