[英]Finding DOM element by partial coordinates
In JavaScript+DOM, if the mouse event happened on a container, but beneath all enclosed elements, how can I efficiently find the enclosed element that is directly above the cursor (same x
, different y
)? 在JavaScript + DOM中,如果鼠标事件发生在容器上但在所有封闭元素之下,那么如何有效地找到位于光标正上方的封闭元素(相同
x
,不同y
)?
Obviously getElementFromPoint
does not help me here (even where available), because I am not going to go up pixel by pixel. 显然,
getElementFromPoint
在这里(即使有可用)也无济于事,因为我不会逐像素增加。 Finding positions of all elements in container can also be rather slow if there are a lot of elements. 如果元素很多,在容器中查找所有元素的位置也可能会很慢。
If you use nested HTML tags like this you could bypass the need to use X,Y coordinates and navigate the DOM instead. 如果使用这样的嵌套HTML标记,则可以绕过使用X,Y坐标并导航DOM的需求。
<ul id="theparent" class="aparent">
<li id="thechild" class="achild">Something</li>
<li id="anotherchild" class="achild">Something</li>
</ul>
<ul id="anotherparent" class="aparent>
<div id="yetanotherchild" class="achild">Something else</li>
</ul>
You could use jquery to bind to each achild
div's onclick event, and then find its immediate parent: 您可以使用jquery绑定到每个子
achild
div的onclick事件,然后找到其直接父级:
$(".achild").bind("click", function() {
$(this).parent().trigger("childclicked");
});
And then you can make something happen for the parent: 然后,您可以为父母做一些事情:
$(".aparent").bind("childclicked", function() {
console.log("a child of mine was clicked");
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.