问题描述
我想检测鼠标在支架 div 中移动时的位置.但是,当我将 mose 移动到支架 div 内的 SVG 元素上时,它将采用与此元素的相对位置,而不是支架 div.任何人都知道我如何防止这种情况?下面看我使用的代码:
I want to detect the position of the mouse in the holder div when it moves. However, when I move my mose over SVG elements within the holder div it will take the relative position to the this element and not the holder div. Anyone an idea how I can prevent this? Below see the code I used:
var R = Raphael("holder", canw, canh);
$('#holder').mousemove(function (event){
if(mousemove){
position = getPosition(event);
console.log(position.x+" - "+position.y);
}
});
function getPosition(e) {
//this section is from http://www.quirksmode.org/js/events_properties.html
console.log(e);
var targ;
if (!e)
e = window.event;
if (e.target)
targ = e.target;
else if (e.srcElement)
targ = e.srcElement;
if (targ.nodeType == 3) // defeat Safari bug
targ = targ.parentNode;
console.log(targ);
// jQuery normalizes the pageX and pageY
// pageX,Y are the mouse positions relative to the document
// offset() returns the position of the element relative to the document
var x = e.pageX - $(targ).offset().left;
var y = e.pageY - $(targ).offset().top;
return {"x": x, "y": y};
};
<div id="holder"></div>
推荐答案
您应该使用 event.currentTarget
而不是 event.target
- 这将为您提供附加侦听器的元素,而不是接收事件的元素.因此,您的位置将相对于 #holder
元素计算.
You should be using event.currentTarget
instead of event.target
- this will give you the element you attached the listener to rather than the element that received the event. So your position will be calculated relative to the #holder
element.
由于您使用的是 jQuery,因此这也应该适用于 Internet Explorer(jQuery 显然 emulate event.currentTarget
那里).也不需要其他 IE 兼容性技巧(window.event
和 event.srcElement
).
Since you are using jQuery this should work in Internet Explorer as well (jQuery apparently emulates event.currentTarget
there). Other IE compatibility hacks (window.event
and event.srcElement
) shouldn't be required either.
这篇关于当鼠标悬停在元素上时,div 上的鼠标移动会发生变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!