I have a square image/graph on which the user clicks.
Is there a way to display the (x,y) coordinates of the cursor to the user in real-time whenever the user hovers over the image (开发者_JAVA百科user does not need to click on the image)?
This should do it:
HTML
<img id="the_image" src="http://placekitten.com/200/200" />
<div id="coords"></div>
Javascript
$image = $('#the_image');
imgPos = [
$image.offset().left,
$image.offset().top,
$image.offset().left + $image.outerWidth(),
$image.offset().top + $image.outerHeight()
];
$image.mousemove(function(e){
$('#coords').html((e.pageX-imgPos[0]) +', '+ (e.pageY-imgPos[1]));
});
DEMO (updated): http://jsfiddle.net/az8Uu/2/
Note: Throttling the mousemove handler would be a good idea too, to avoid calling the function every 4 milliseconds.
Here you go:
HTML:
<img class="coords" src="http://i.imgur.com/bhvpy.png">
JavaScript:
var tooltip = $( '<div id="tooltip">' ).appendTo( 'body' )[0];
$( '.coords' ).
each(function () {
var pos = $( this ).position(),
top = pos.top,
left = pos.left,
width = $( this ).width(),
height = $( this ).height();
$( this ).
mousemove(function ( e ) {
var x, y;
x = ( ( e.clientX - left ) / width ).toFixed( 1 ),
y = ( ( height - ( e.clientY - top ) ) / height ).toFixed( 1 );
$( tooltip ).text( x + ', ' + y ).css({
left: e.clientX - 30,
top: e.clientY - 30
}).show();
}).
mouseleave(function () {
$( tooltip ).hide();
});
});
Live demo: http://jsfiddle.net/pSVXz/12/
With my updated code, you can have multiple images with this functionality - just add the class "coords"
to the images.
Note: This code has to be inside the load
handler (instead of the ready
) handler, because we have to read the image's dimensions which we can only do for fully loaded images.
Depending on your requirements, something based on :
$("img").mousemove(function(e) {
console.log(e.layerX + ", " + e.layerY);
});
精彩评论