找到相对于元素的鼠标位置 [英] Find mouse position relative to element

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

问题描述

我想用画布制作一个小画画应用程序。所以我需要在画布上找到鼠标的位置。

I want to make a little painting app using canvas. So I need to find the mouse's position on the canvas.

推荐答案

对于使用JQuery的人:

有时候,如果您有嵌套元素,其中一个元素附加了事件,那么理解浏览器看作父母的内容可能会令人困惑。在这里,您可以指定哪个父项。

Sometimes, when you have nested elements, one of them with the event attached to it, it can be confusing to understand what your browser sees as the parent. Here, you can specify which parent.

您获取鼠标位置,然后从父元素的偏移位置中减去它。

You take the mouse position, and then subtract it from the parent element's offset position.

var x = evt.pageX - $('#element').offset().left;
var y = evt.pageY - $('#element').offset().top;

如果您试图在滚动窗格内的页面上获取鼠标位置:

If you're trying to get the mouse position on a page inside a scrolling pane:

var x = (evt.pageX - $('#element').offset().left) + self.frame.scrollLeft();
var y = (evt.pageY - $('#element').offset().top) + self.frame.scrollTop();

或相对于页面的位置:

var x = (evt.pageX - $('#element').offset().left) + $(window).scrollLeft();
var y = (evt.pageY - $('#element').offset().top) + $(window).scrollTop();

请注意以下性能优化:

var offset = $('#element').offset();
// Then refer to 
var x = evt.pageX - offset.left;

通过这种方式,JQuery不必查找#每行的元素

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

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