开发者

How could I display (x,y) coordinates on image in real-time to the user when the user hovers his mouse over the image?

开发者 https://www.devze.com 2023-04-04 14:56 出处:网络
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百科us

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);
});
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号