当用户将鼠标hover在图像上时,如何实时向用户显示图像上的(x,y)坐标?

我有一个用户点击的方形图像/图形。

有没有办法在用户将鼠标hover在图像上时(用户不需要点击图像)实时向用户显示光标的(x,y)坐标?

干得好:

HTML:

 

JavaScript的:

 var 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(); }); });

现场演示: http //jsfiddle.net/pSVXz/12/

使用我更新的代码,您可以拥有具有此function的多个图像 – 只需将类"coords"添加到图像即可。

注意:此代码必须位于load处理程序(而不是ready )处理程序中,因为我们必须读取图像的尺寸,我们只能对完全加载的图像执行此操作。

这应该这样做:

HTML

  

使用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])); }); 

演示 (更新): http : //jsfiddle.net/az8Uu/2/

注意: 限制 mousemove处理程序也是一个好主意,以避免每4毫秒调用一次该函数。

根据您的要求,基于以下内容:

 $("img").mousemove(function(e) { console.log(e.layerX + ", " + e.layerY); });