使用JavaScript / jQuery在keydown上获取X,Y坐标

我正在开发一个富文本编辑器.当用户在触发事件的位置按下ctrl空格键时,我想打开用户定义的上下文菜单.

我没有得到这次活动的坐标.

是否有可能获得事件坐标?

这是我的示例代码

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.js"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.js"></script>
    <style>
        #edit{
         border:1px solid red;
         width:500px;
            height:300px;
        }
        #ctxMenu{
         display: none;
         position: absolute;
         border: 1px solid #000000;
        }
        #ctxMenu ul li{
           list-style: none;
        }
    </style>
</head>
<body>
  <div id="edit" contenteditable="true">

  </div>
  <div id="ctxMenu">
      <ul>
          <li>One</li>
          <li>Two</li>
          <li>Three</li>
          <li>Four</li>
      </ul>
  </div>

 <script>
     $('#edit').keydown(function(e){
         /**** get x, y coordinates.
          *
          */
         if (e.ctrlKey && e.keyCode == 32) {
            $('#ctxMenu').show().css({left:x,top:y});
         }
     });
 </script>
</body>
</html>

最佳答案
HERE-JSFIDDLE是您的CODE的输出.

要么

JS CODE(只需用下面的代码替换你的js代码.)

$(document).ready(function(){
  $('#edit').bind('keydown', function(e){
    var $this = $(this);
    var a = $this.data('mousepos').x;
    var b = $this.data('mousepos').y;
    if (e.ctrlKey && e.keyCode == 32) {  
        $('#ctxMenu').show().css({left:a,top:b});
    }else{
        $('#ctxMenu').hide();
    }
  });

  $('#edit').bind('mousemove', function(e){
    $(e.target).data('mousepos', {x: e.pageX, y: e.pageY});
  });
});
点赞