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);
我在这里尝试用这段代码做的是获取我的可拖动元素试图放入的元素(当前悬停在上面).但是,这将始终返回我的可拖动对象,而不是它下面的表格单元格 (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屋!