如何在按下鼠标的情况下创建按键认为已按下的行为?

时间:2016-10-13 16:50:27

标签: javascript jquery babylonjs

我有一个babylonjs 3D场景,其中某些按键在按下时会导致相机向前/向后导航等。例如,按T可向前移动观看者。

我正在尝试生成一种效果,只要窗口中的任何地方发生了mousedown,T键就会认为它已经被按下了。总之,我需要mousedown来向前移动相机。

 document.addEventListener("mousedown", function(e) {
   var code = 116;//T
   $('document').trigger(
     jQuery.Event('keypress', {
       keyCode: code,
       which: code
     })
   );
   $("#show").append("mousedown creates: " + code + "<BR>");
 });

 document.addEventListener("keypress", function(e) {
   var key = e.which;
   //If it's the T key
   if (key == 116) {
     $("#show").append("T key has been pressed<BR>");
   }
 });

 // I would like the mousedown event to fire the keypress event 
 // as if the T key has been pressed

小提琴是here

1 个答案:

答案 0 :(得分:0)

当按键事件似乎发生时,这有点接近。然而,密码并没有通过。输出显示&#34; key:undefined。&#34;

 function fire(type, options) {
   var event = new CustomEvent(type);
   for (var p in options) {
    event[p] = options[p];
   }
   this.dispatchEvent(event);
 }

 window.addEventListener("mousedown", function(e) {
   fire("keypress", {
    keyCode: 116,
    bubbles: true
   })
 });

 window.addEventListener("keypress", function(e) {
   var key = e.which;
   $("#show").append("key: " + key + "<BR>");
   if (key == 116) {
    $("#show").append("T key was pressed<BR>");
   }
 });

小提琴是 here