如何获取鼠标位置-相对于元素 [英] How to get mouse position - relative to element

查看:410
本文介绍了如何获取鼠标位置-相对于元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获取鼠标相对于光标所在元素的位置.

I would like to get the mouse position, relative to the element the cursor is in.

以下代码捕获了鼠标相对于页面的位置.

The following code capture the position where mouse is relative to the page.

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

http://api.jquery.com/mousemove/

推荐答案

尝试一下 JSFiddle

您需要包括.js文件才能使用此代码: Jquery-2.1.1. js

You need to include .js file for using this code: Jquery-2.1.1.js

相对鼠标位置的代码在此处:

For Relative mouse position the code is here:

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+")");
});

这篇关于如何获取鼠标位置-相对于元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆