Get mouse position when focus/blur events are fired? - Javascript/jQuery

萝らか妹 提交于 2019-12-01 16:42:29

问题


I'm using jquery to catpure an event:

$('input').focus(function(e){

    console.log( e.pageX, e.pageY );

});

This doesn't seem to work... any ideas on alternative ways to getting the mouse position?


Help would be great, thanks :)


回答1:


You can only get mouse coordinates using mouse events. If you want to capture the position of the mouse, you can use a global mousemove event listener, and store the coordinates in a set of variables, which can later be accessed by the focus function. Example:

var pageX, pageY; //Declare these globally
$(window).mousemove(function(e){
    pagex = e.pageX;
    pageY = e.pageY;
});

$('input').focus(function(){
    console.log(pageX, pageY); // These variables have been defined by the global
                               //  mousemove event
});



回答2:


If you're trying to get the position relative to the element, try something like this instead:

$("input").focus(function(e){
    var relativeX = e.pageX - this.offsetLeft;
    var relativeY = e.pageY - this.offsetTop;
});


来源:https://stackoverflow.com/questions/7984725/get-mouse-position-when-focus-blur-events-are-fired-javascript-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!