Вы можете использовать jQuery-метод event.pageX
и event.pageY
в сочетании с jQuery-методом offset()
, чтобы получить положение указателя мыши относительно элемента.
Давайте посмотрим на следующий пример, чтобы понять, как это работает:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Get Coordinates of Mouse Pointer</title>
<style>
#box{
width:400px;
height:300px;
background: #f2f2f2;
border: 1px solid #000;
}
</style>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
$(document).ready(function() {
$("#box").mousemove(function(event){
var relX = event.pageX - $(this).offset().left;
var relY = event.pageY - $(this).offset().top;
var relBoxCoords = "(" + relX + "," + relY + ")";
$(".mouse-cords").text(relBoxCoords);
});
});
</script>
</head>
<body>
<div id="box"></div>
<p>Координаты указателя мыши относительно блока DIV: <strong class="mouse-cords"></strong></p>
</body>
</html>