当你有重叠元素时从点获取元素? [英] Get element from point when you have overlapping elements?

查看:101
本文介绍了当你有重叠元素时从点获取元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您可以使用它来查找给定点的文档元素

You can use this to find a document element at a given point

document.elementFromPoint(x, y);

如果点上有重叠元素,你能做什么? (我知道这不是一个很好的做事方式 - 在截止日期之前尝试一个针对错误的hackish解决方法)。

What can you do if there are overlapping elements at the point? (I know this is not a great way to do things -- trying a hackish workaround for a bug before a deadline).

推荐答案

我想你已经知道了, document.elementFromPoint(x,y); 只返回与该点重叠的最顶层元素。

As I think you already know, document.elementFromPoint(x, y); only returns the top-most element that overlaps that point.

如果你要做的是找到与给定点重叠的所有元素,即使是其他元素背后的元素,那么我也不知道任何可以为你做的DOM功能。你可能要写自己的。

If what you're trying to do is find all elements that overlap with a given point, even elements behind other elements, then I'm not aware of any DOM function that will do that for you. You may have to write your own.

有点hackish版本会调用 elementFromPoint(x,y),记住DOM项目,然后隐藏那个带的项目显示:无,然后再次调用 elementFromPoint(x,y),直到你得到的是身体,然后恢复你隐藏的物品。

A somewhat hackish version would be to call elementFromPoint(x,y), remember that DOM item, then hide that item with display: none, then call elementFromPoint(x,y) again until all you get is the body, then restore the items you hid.

一个不太讨厌的版本是循环浏览页面中的所有对象并将它们在页面中的偏移/高度/宽度与你的点进行比较。

A less hackish version would be to cycle though all objects in the page and compare their offset/height/width in the page to your point.

这是一种方法:

function getAllElementsFromPoint(x, y) {
    var elements = [];
    var display = [];
    var item = document.elementFromPoint(x, y);
    while (item && item !== document.body && item !== window && item !== document && item !== document.documentElement) {
        elements.push(item);
        display.push(item.style.display);
        item.style.display = "none";
        item = document.elementFromPoint(x, y);
    }
    // restore display property
    for (var i = 0; i < elements.length; i++) {
        elements[i].style.display = display[i];
    }
    return elements;
}

工作演示: http://jsfiddle.net/jfriend00/N9pu9/

这篇关于当你有重叠元素时从点获取元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆