【问题标题】:Get element at specified position - JavaScript获取指定位置的元素 - JavaScript
【发布时间】:2010-11-18 13:51:31
【问题描述】:

使用 Javascript 如何识别给定位置的元素?基本上我正在寻找一个函数,它接受两个输入参数(x 和 y 坐标)并返回参数表示的屏幕上位置的 html 元素。

【问题讨论】:

标签: javascript html dom


【解决方案1】:

【讨论】:

  • 我很惊讶这在 ie 5.5 中可以工作,而且今天用得不多。
  • 我试过这个方法,它根据文件测量位置。如何相对于父元素使用它?
  • 如果在坐标x,y,有frame或者iframe你会得到frame,而不是那个位置的元素。
  • 一个 jsfiddle 的例子真的很棒!看起来很神奇!迫不及待想试试!
【解决方案2】:

要获取相对于视口的特定位置的最顶部元素,可以使用document.elementFromPoint(x, y)

要获取特定位置的所有元素的数组,请使用document.element<b><i>s</i></b>FromPoint(x, y)

在这两种情况下,x 是相对于视口左侧的水平坐标,y 是相对于视口顶部的垂直坐标。

【讨论】:

    【解决方案3】:

    您可以使用原生 JavaScript elementFromPoint(x, y) 方法,该方法返回视口中坐标 x,y 处的元素。

    elementFromPoint w3c draft

    还有一个代码示例:

    function changeColor(newColor) {
        // Get the element placed at coords (2, 2)
        var elem = document.elementFromPoint(2, 2);
        // Set the foreground color to the element
        elem.style.color = newColor;
    }
    <p id="para1">Change this text color using the following buttons.</p>
    <button onclick="changeColor('blue');">Blue</button>
    <button onclick="changeColor('red');">Red</button>

    您可以使用setInterval()不断检查元素的悬停事件但不推荐,尝试使用.hover(...)和css代替以增强应用程序性能。

    【讨论】:

      猜你喜欢
      • 2010-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-26
      相关资源
      最近更新 更多