在javascript中获取相对鼠标X/Y
我在页面的某个地方有一个 div 。然后我得到鼠标 XY:
var relativeMouseX = self.gCurrentMouseX - self.gContainerLeft;
var relativeMouseY = self.gCurrentMouseY - self.gContainerTop;
当前的 mousex/y 是通过以下方式获得的:
// Update mouse coords
this.gUpdateMousePos = function(evt) {
if (evt === undefined) evt = window.event;
if (window.event) {
this.gCurrentMouseX = event.clientX;
this.gCurrentMouseY = event.clientY;
}
else {
this.gCurrentMouseX = evt.clientX;
this.gCurrentMouseY = evt.clientY;
}
}
这在测试中工作得很好,但是当 div 位于页面下方时,它会弄乱鼠标 X/Y,因为坐标似乎只是在viewingwg区域而不是整个页面。
X 坐标工作正常,因为页面永远不会水平扩展得比浏览器大小更宽,但垂直扩展是一个问题!
关于如何获取相对于元素的鼠标 X/Y 有什么想法吗?
I have a div somewhere on the page. I then get the mouse XY:
var relativeMouseX = self.gCurrentMouseX - self.gContainerLeft;
var relativeMouseY = self.gCurrentMouseY - self.gContainerTop;
Where the current mousex/y are obtained via:
// Update mouse coords
this.gUpdateMousePos = function(evt) {
if (evt === undefined) evt = window.event;
if (window.event) {
this.gCurrentMouseX = event.clientX;
this.gCurrentMouseY = event.clientY;
}
else {
this.gCurrentMouseX = evt.clientX;
this.gCurrentMouseY = evt.clientY;
}
}
This worked fine in testing, but when the div is located down a page, it messes up themouse X/Y, as the co-ordinates only seem to be in the viewinwg area and not the entire page.
X co-ord works fine, because the pages never expand horizontally wider than the browser size, but vertical is a problem!
Any ideas how to get mouse X/Y relative to the element?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
event.clientX+document.body.scrollLeft
和event.clientX+document.body.scrollTop
或
event.pageX
和event.pageY
第一个只是将当前滚动位置添加到值中,第二个是相对于页面而不是客户端窗口的鼠标位置。
event.clientX+document.body.scrollLeft
andevent.clientX+document.body.scrollTop
or
event.pageX
andevent.pageY
The first one is just adding current scroll position to the value, the second one is the mouse position relative to the page, not the client window.
您需要考虑父元素才能找到子元素在页面上的真实位置。请参阅http://www.quirksmode.org/js/findpos.html
You need to account for the parent elements to find a child element's true position on the page. See http://www.quirksmode.org/js/findpos.html