我想获得相对于光标所在元素的鼠标位置。
以下代码捕获鼠标相对于页面的位置。
$( "div" ).mousemove(function( event ) {
var pageCoords = "( " + event.pageX + ", " + event.pageY + " )";
var clientCoords = "( " + event.clientX + ", " + event.clientY + " )";
$( "span:first" ).text( "( event.pageX, event.pageY ) : " + pageCoords );
$( "span:last" ).text( "( event.clientX, event.clientY ) : " + clientCoords );
});
答案 0 :(得分:6)
试试这个JSFiddle
您需要包含.js文件才能使用此代码:Jquery-2.1.1.js
对于相对鼠标位置,代码在此处:
var x,y;
$("#div1").mousemove(function(event) {
var offset = $(this).offset();
x = event.pageX- offset.left;
y = event.pageY- offset.top;
$("#div1").html("(X: "+x+", Y: "+y+")");
});
答案 1 :(得分:1)
HTML http://jsfiddle.net/1gzdkg9p/
<div id="result"></div>
Jquery
jQuery(function($) {
var currentMousePos = { x: -1, y: -1 };
$(document).mousemove(function(event) {
currentMousePos.x = event.pageX;
currentMousePos.y = event.pageY;
$("#result").html("X: "+currentMousePos.x+" Y : "+currentMousePos.y);
});
});
答案 2 :(得分:0)
看看这个Fiddle。 [编辑]
您必须获取鼠标的坐标,然后减去元素的偏移量以获得相对值。
<强> HTML:强>
<div class="test"></div>
<强> JS:强>
$(document).on('mousemove','.test', function(e){
var offset = $(this).offset();
var relativeX = e.pageX - offset.left;
var relativeY = e.pageY - offset.top;
var wide = $(this).width();
var tall = $(this).height();
var percentX = (relativeX*100)/wide;
var percentY = (relativeY*100)/tall;
console.log(percentX+", "+percentY);
});
<强> CSS:强>
.test{
background-color: #000000;
width: 50%;
height: 50px;
margin-left: 40px;
margin-top: 20px;
}