I suggest you take a look at http://www.zehnet.de/2010/11/19/document-elementfrompoint-a-jquery-solution/ which is a full implementation.
Creating mousedown event with global scope
-
29-03-2022 - |
문제
I am hacking on something to fix another problem that is a constraint of the system. Not ideal, but..
Anyway, I need to generate a click/touch then find out the topmost element under the poing (300, 300)
. I am using:
event = $.Event( "mousedown", { pageX:300, pageY:300 } );
$("window").trigger( event );
Then I am listening for:
$(window).bind 'mousedown', (jQueryEvent)->
console.log jQueryEvent.target
However, event.target
is always returning window. This makes sense. However, what I am trying to do is generate a mousedown event on the whole page, then use event.target
to find out which element is under the (pageX, pageY)
. Is there a way to do this?
해결책
다른 팁
Have you looked at document.elementFromPoint? This might be a clean approach to find your element at a particular position.
https://developer.mozilla.org/en-US/docs/DOM/document.elementFromPoint
pageX and pageY are on the event variable itself, not on the target. But they get overwritten by the mousedown event. You dont need to create an event for this, closure will work just fine:
function hotspot (a, b) {
var x = a[0] || 0;
var y = a[1] || 0;
var w = b[0] || 0;
var h = b[1] || 0;
function between (x2, y2) {
return x2 >= x &&
y2 >= y &&
x2 <= (x + w) &&
y2 <= (y + h);
}
return function (e) {
console.log("mouse x y:", e.pageX, e.pageY);
console.log("target x y w h:", x, y, w, h);
console.log(between(e.pageX, e.pageY));
}
}
$(document).on('mousedown', hotspot([0,0], [300,300]));
Edit: re-reading your question, I just don't know what you are trying to achieve.