Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
480 views
in Technique[技术] by (71.8m points)

javascript - 在HTML DOM树中查找元素A是否在元素B之后(Find if element A is behind element B in HTML DOM tree)

Having an arbitrary pair of colliding elements (by rects) in DOM tree, how to find which one of them is in front and which one is behind?(在DOM树中有一对任意的碰撞元素(通过rects),如何找到其中的哪个在前面,哪个在后面?)

Given el1 and el2 in DOM tree and knowing overlap points using el1.getBoundingClientRect() and el2.getBoundingClientRect() one can find the overlap rect.(给定DOM树中的el1el2并使用el1.getBoundingClientRect()el2.getBoundingClientRect()知道重叠点, el2.getBoundingClientRect()可以找到重叠矩形。) However having (x,y) point inside overlap rect document.elementFromPoint(x,y) returns just one element, which is in front of others at the given point.(但是,在重叠rect document.elementFromPoint(x,y)有(x,y)点.elementFromPoint document.elementFromPoint(x,y)仅返回一个元素,该元素在给定点位于其他元素的前面。) This element can be neither el1 nor el2 .(该元素不能是el1el2 。) So if one needs to find if el1 is in front of el2 or vice versa, this approach does not work.(因此,如果需要确定el1是否位于el2 ,反之亦然,则此方法不起作用。)   ask by progmastery translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use document.elementsFromPoint() (note the s ), this will return an Array with all the elements that can be pointed to at these coordinates, ordered by z-index.(使用document.elementsFromPoint() (注意s ),这将返回一个Array,其中包含可以在这些坐标处指向的所有元素,并按z-index排序。)

onclick = e => { console.log( document.elementsFromPoint( e.clientX, e.clientY ) ); } .container div { width: 100px; height: 100px; border: 1px solid; position: absolute; opacity: 0.5; } .A { background: red; top: 0; left: 0; } .B { background: green; top: 50px; left: 50px; } .C { background: blue; top: 25px; left: 25px; } <div class="container"> <div class="A"></div> <div class="B"></div> <div class="C"></div> </div> You can then filter this Array as you wish to make it contain only some elements and compare their position in that Array, though beware MS implementations return a NodeList, so you may need to reduce it to an Array first.(然后,您可以过滤该数组,以使其仅包含一些元素并比较它们在该数组中的位置,尽管要注意MS实现会返回NodeList,所以您可能需要先将其缩减为一个Array。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...