【发布时间】:2011-11-16 22:00:26
【问题描述】:
我有一个用户点击的方形图像/图表。
有没有办法在用户将鼠标悬停在图像上时实时向用户显示光标的 (x,y) 坐标(用户不需要点击图像)?
【问题讨论】:
-
查看以下链接以获得您问题的答案:emanueleferonato.com/2006/09/02/…
标签: javascript jquery ajax image
我有一个用户点击的方形图像/图表。
有没有办法在用户将鼠标悬停在图像上时实时向用户显示光标的 (x,y) 坐标(用户不需要点击图像)?
【问题讨论】:
标签: javascript jquery ajax image
根据您的要求,基于:
$("img").mousemove(function(e) {
console.log(e.layerX + ", " + e.layerY);
});
【讨论】:
应该这样做:
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(更新):http://jsfiddle.net/az8Uu/2/
注意:Throttling mousemove 处理程序也是一个好主意,以避免每 4 毫秒调用一次函数。
【讨论】:
给你:
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();
});
});
现场演示: http://jsfiddle.net/pSVXz/12/
使用我更新的代码,您可以拥有多个具有此功能的图像 - 只需将 "coords" 类添加到图像。
注意:此代码必须在 load 处理程序(而不是 ready)处理程序内,因为我们必须读取图像的尺寸,而这只能用于完全加载的图像。
【讨论】: