jQuery获取元素内的鼠标位置 [英] jQuery get mouse position within an element

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

问题描述

我希望制作一个控件,使用户可以在div内单击,然后拖动鼠标,然后放开鼠标以指示他们想要放置多长时间. (这是用于日历控件的,因此用户将及时显示某个事件的时长)

I was hoping to craft a control where a user could click inside a div, then drag the mouse, then let up on the mouse in order to indicate how long they want something to be. (This is for a calendar control, so the user will be indicating the length, in time, of a certain event)

执行此操作的最佳方法似乎是在父div上注册"mousedown"事件,然后在div上注册"mousemove"事件,直到触发"mouseup"事件为止. "mousedown"和"mouseup"事件将定义时间范围的开始和结束,当我跟随"mousemove"事件时,我可以动态更改范围的大小,以便用户可以看到他们在做什么.我的依据是如何在Google日历中创建事件.

It looks like the best way to do this would be to register a "mousedown" event on the parent div that in turn registers a "mousemove" event on the div until a "mouseup" event is triggered. The "mousedown" and "mouseup" events will define the start and end of the time range and as I follow "mousemove" events, I can dynamically change the size of the range so that the user can see what they are doing. I based this off of how events are created in google calendar.

我遇到的问题是jQuery事件似乎仅提供了引用整个页面的可靠鼠标坐标信息.有什么方法可以识别相对于父元素的坐标?

The issue I'm having is that the jQuery event seems to only provide reliable mouse coordinate information in reference to the whole page. Is there any way to discern what the coordinates are in reference to the parent element?

以下是我要执行的操作的图片:

Heres a picture of what I'm trying to do:

推荐答案

一种方法是使用jQuery 方法来翻译 event.pageX

One way is to use the jQuery offset method to translate the event.pageX and event.pageY coordinates from the event into a mouse position relative to the parent. Here's an example for future reference:

$("#something").click(function(e){
   var parentOffset = $(this).parent().offset(); 
   //or $(this).offset(); if you really just want the current element's offset
   var relX = e.pageX - parentOffset.left;
   var relY = e.pageY - parentOffset.top;
});

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

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