javascript - elementFromPoint选择底部元素 [英] javascript - elementFromPoint select bottom element
问题描述
我正在使用jquery / javascript处理这个拖放应用程序,我不得不使用两者的平衡来完成我想要的。
I'm working on this drag and drop application with jquery/javascript, and I'm having to use a balance of the two to accomplish what I want.
var drop = document.elementFromPoint($(this).offset()。left,$(this).offset()。top);
我在这里尝试使用这个代码来获取我的draggable试图放入的元素(目前正在盘旋)。但是,这将始终返回我的draggable,而不是它下面的表格单元格( td
)。
what I'm trying to do with this code here is to get the element that my draggable is trying to be dropped in (is currently hovering over). This, however, will always return my draggable, as opposed to the the table cell (td
) underneath it.
因为我知道我正在寻找 td
元素,有没有办法将 var drop
设置为类似:
Since I know I am looking for a td
element, is there a way to set var drop
to be something like:
var drop = document.elementFromPoint(x,y,'td')
?
还是有更好的方法可以做到这一点吗?
Or is there a better way to go about doing this?
推荐答案
自 document.elementFromPoint
返回最顶层的元素,你需要暂时将你的draggable设置为 display:none
或 pointer-events:none
查找它下面的元素。我在下面创建了一个要点,它返回给定点上所有元素的列表。
Since document.elementFromPoint
returns the topmost element, you'll need to temporarily set your draggable to display:none
or pointer-events:none
to find elements below it. I've created a gist below that returns a list of all elements at a given point.
尝试
var elementsArray = KoreSampl.atPoint(x,y,yourTableElement);
或
var elementsArray = KoreSampl.fromEvent(dropEvent, yourTableElement);
然后
for(var i=0; i<elementsArray.length; i++) {
//loop through elementsArray until you find the td you're interested in
}
使用下面的要点: https://gist.github.com/2166393
;(function(){
//test for ie: turn on conditional comments
var jscript/*@cc_on=@_jscript_version@*/;
var styleProp = (jscript) ? "display" : "pointerEvents";
var KoreSampl = function() {};
KoreSampl.prototype.fromEvent = function(e, lastElement) {
e = e || window.event; //IE for window.event
return this.atPoint(e.clientX, e.clientY, lastElement);
};
KoreSampl.prototype.atPoint = function(clientX, clientY, lastElement) {
//support for child iframes
var d = (lastElement) ? lastElement.ownerDocument : document;
//the last element in the list
lastElement = lastElement || d.getElementsByTagName("html")[0];
var element = d.elementFromPoint(clientX, clientY);
if(element === lastElement || element.nodeName === "HTML") {
return [element];
} else {
var style= element.style[styleProp];
element.style[styleProp]="none"; //let us peak at the next layer
var result = [element].concat(this.atPoint(clientX,clientY,lastElement));
element.style[styleProp]= style; //restore
return result;
}
};
window["KoreSampl"] = new KoreSampl();
})();
这篇关于javascript - elementFromPoint选择底部元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!