2015-04-20 70 views
3

如果我有jQuery監聽「外部」元素上的mousemove事件,則offsetXoffsetY值會在鼠標位於該元素內時提供相對於「內部」元素的偏移量內部元素和事件冒泡給處理程序。jQuery mousemove相對於冒泡事件上的監聽元素的偏移量

我怎樣才能總是得到相對於處理程序所附的元素的偏移?

例子: http://jsfiddle.net/00mo3eeu/

HTML

<div class="outer"> 
    <div class="inner"></div> 
</div> 

CSS

.outer { 
    background: red; 
    width: 300px; 
    height: 400px; 
    margin: 40px; 
} 

.inner { 
    background: blue; 
    width: 100px; 
    height: 150px; 
    margin: 70px; 
    display: inline-block; 
} 

JS

$('.outer').mousemove(function(e) { 
    console.log([e.offsetY, e.offsetX]); 
}); 

更新:如果現在還不清楚,弄ŧ即使在藍色方框中,他也可以跟着指針http://jsfiddle.net/00mo3eeu/1/

+0

試試這可能嗎?http://stackoverflow.com/questions/5389527/how-to-get-offset-relative-to-a-specific-parent – Dhiraj

回答

5

這是我當前的解決方案,我歡迎任何改進它的建議。

function (e) { 
    var y = e.pageY - $(e.currentTarget).offset().top 
    var x = e.pageX - $(e.currentTarget).offset().left 
    ... 
} 

理想情況下,這將作爲事件對象的屬性之一給出,但我找不到匹配的一個。