最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin2浏览0评论

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 (user does not need to click on the image)?

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 (user does not need to click on the image)?

Share Improve this question edited Sep 14, 2011 at 10:55 oxo asked Sep 14, 2011 at 10:41 oxooxo 4,45111 gold badges33 silver badges35 bronze badges 1
  • 1 Check out the following link for an answer to your question: emanueleferonato.com/2006/09/02/… – Javier Commented Sep 14, 2011 at 10:44
Add a comment  | 

3 Answers 3

Reset to default 8

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)

  1. 暂无评论