zjm1126
zjm1126

Reputation: 66667

how to get the mouse's offset when i mouseover a element..use jquery

this is my code and have a error:

    $('#map_canvas').mouseover(function(e){
        console.log(e.offset().left+'  '+e.offset().top)
        })

thanks


i do this ,and it is always log (0, 0):

$('#map_canvas').mouseover(function(e){
var offset = $('#map_canvas').offset(); 
console.log(offset.top+'  '+offset.left); //offset of 'realtiveDiv'
console.log(e.pageX +'  '+e.pageY); // mouse position absolute
})

why?

thanks

Upvotes: 1

Views: 7512

Answers (1)

N 1.1
N 1.1

Reputation: 12534

$('#map_canvas').mouseover(function(e){
    var offset = $('#map_canvas').offset(); 
    var x = e.pageX - offset.left;
    var y = e.pageY - offset.top;

    console.log('X: '+x+' Y: '+y); //you want this

    //console.log(offset.top+'  '+offset.left); //offset of 'realtiveDiv'
    //console.log(e.pageX +'  '+e.pageY); // mouse position absolute
});

Update:
if offset.top and offset.left log (0, 0), it means that the element whose offset you are logging, starts at (0, 0). In other words, the element is at the top left corner of the screen.

Upvotes: 3

Related Questions