如何计算与DIV位置相关的鼠标坐标

时间:2021-12-09 20:31:26

I have a DIV and I can get the offset using .offset().

我有一个DIV,我可以使用.offset()获得偏移量。

But I am trying to get the position of the mouse related to the div. When I hover the DIV i can get the x and y offsets of Mouse. But those will be calculated related to Document. But it should be calculated in below way.

但我试图获得与div相关的鼠标位置。当我将鼠标悬停在DIV上时,我可以获得鼠标的x和y偏移量。但那些将与Document相关的计算。但它应该以下面的方式计算。

 For example DIV dimensions are 200 and 200.
 then it should calculate offsets related to (0,200)(200,0),(200,200),(200,200).

Please help me on this. How I can do this.

请帮帮我。我怎么能这样做

1 个解决方案

#1


6  

Do you mean:

你的意思是:

$('#someele').click(function(e) {
  var offset = $(this).offset();
  var x = Math.floor(e.pageX - offset.left);
  var y = Math.floor(e.pageY - offset.top);
  console.log('x pos:' +  x  + ' y pos:' + y);
});

#1


6  

Do you mean:

你的意思是:

$('#someele').click(function(e) {
  var offset = $(this).offset();
  var x = Math.floor(e.pageX - offset.left);
  var y = Math.floor(e.pageY - offset.top);
  console.log('x pos:' +  x  + ' y pos:' + y);
});