How could I display a crosshair cursor with x-y coordinates when hovering over an image?
I have an image inside a div on which users can click.
开发者_StackOverflowIs there a way to display the coordinates of the cursor when hovering over that image in realtime? I know that to display a crosshair cursor, the cursor type has to be set: cursor: crosshair
- but how could I display those coordinates as well?
Try:
$(function () {
$('#hover-img')
// show the coordinates box on mouseenter
.bind('mouseenter', function () {
$('#coordinates').show();
})
// hide it on mouseleave
.bind('mouseleave', function () {
$('#coordinates').hide();
})
// update text and position on mousemove
.bind('mousemove', function (evt) {
$('#coordinates').html(
(evt.pageX - this.offsetLeft) + '/' + (evt.pageY - this.offsetTop)
).css({
left: evt.pageX + 20,
top: evt.pageY + 20
})
});
});
Note: see the » demo for the html-elements used.
<html>
<head>
<script>
function onMouseOver(Sender,e){
var x = e.x - Sender.offsetLeft;
var y = e.y - Sender.offsetTop;
document.getElementById('coord').innerHTML = x+"-"+y;
}
</script>
</head>
<body>
<img src="image.jpg" onmousemove="onMouseOver(this,event)">
<span id='coord'></span>
</body>
</html>
With jQuery you can do:
<script language="text/javascript">
$('#your_image').mouseover(function(e){
var x = e.pageX - this.offsetLeft;
var y = e.pageY - this.offsetTop;
alert("X: " + x + " Y: " + y);
});
</script>
<html>
<head>
<script type="text/javascript">
function getAbsoluteOffset(htmlelement) {
var offset={x:htmlelement.offsetLeft,y:htmlelement.offsetTop};
while(htmlelement=htmlelement.offsetParent)
{
offset.x+=htmlelement.offsetLeft;
offset.y+=htmlelement.offsetTop;
}
return offset;
}
function image_onmouseout(ev) {
document.getElementById("mouseinfo").innerHTML="Mouse outside of image";
}
function image_onmousemove(ev) {
var offset=getAbsoluteOffset(this);
document.getElementById("mouseinfo").innerHTML=
"Coordinates in page: (x: "+ev.clientX+",y:"+ev.clientY+")"+
"<br/>"+
"Coordinates in image: (x: "+(ev.clientX-offset.x)+",y:"+(ev.clientY-offset.y)+")";
}
</script>
</head>
<body>
<div style="width:400px;height:400px;background:red;">
<img src="image.png"
onmouseout="image_onmouseout.call(this,event);"
onmousemove="image_onmousemove.call(this,event);" />
</div>
<span id="mouseinfo">Mouse outside of image</span>
</body>
</html>
example: http://jsfiddle.net/HWMtc/
精彩评论