[英]Getting x and y position of mouse pointer relative to an element
Hi can anyone help with this?嗨,有人可以帮忙吗?
When I move the mouse pointer of a element, I would like to retrieve the x and y positions relative to the <div>
当我移动一个元素的鼠标指针时,我想检索相对于
<div>
的 x 和 y 位置
Eg - when I put the mouse pointer at the top left point of the div I would expect to get an X of 1 and a Y of 1.例如 - 当我将鼠标指针放在 div 的左上角时,我希望得到 X 为 1 和 Y 为 1。
This needs to be compatible for Internet Explorer这需要与 Internet Explorer 兼容
Thanks all for your time.感谢大家的时间。
This works, trouble was I was calling it from the onclick event which didnt give the scrollLeft and scrollTop values.这有效,问题是我是从 onclick 事件调用它的,它没有给出 scrollLeft 和 scrollTop 值。 I should be able to get the position from this by using the calculations of the Divs top and left values.
我应该能够通过使用 Divs 顶部和左侧值的计算来获得位置。
function getMouseXY(ctrl)
{
var tempX = event.clientX + document.body.scrollLeft;
var tempY = event.clientY + document.body.scrollTop;
document.getElementById('<%=txtXPos.ClientID%>').value = tempX;
document.getElementById('<%=txtXPos.ClientID%>').value = tempY;
}
Thanks to all except LincolnK !感谢除了 LincolnK 之外的所有人! !
! lol
哈哈
It's work for me:这对我有用:
function getOffset( el )
{
var _x = 0;
var _y = 0;
while( el && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) )
{
_x += el.offsetLeft - el.scrollLeft;
_y += el.offsetTop - el.scrollTop;
el = el.offsetParent;
}
return { top: _y, left: _x };
}
var x = getOffset( document.getElementById('MY DIV ID') ).left;
var Y = getOffset( document.getElementById('MY DIV ID') ).top;
function myOnYourEvent()
{
var relativeX = window.event.clientX;
var relativeY = window.event.clientY;
var my_div_x = relativeX - x;
var my_div_y = relativeY - Y;
alert(my_div_x + " " + my_div_y);
}
You could try something like this你可以试试这样的
function myOnMouseMove(element) {
var e = window.event
var relativeX = e.screenX - element.scrollLeft;
var relativeY = e.screenY - element.scrollTop;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.