Chrome如何确定关键字事件目标?

时间:2014-12-19 15:16:12

标签: javascript google-chrome javascript-events

所以,在得知GitHub.com绑定" L"关键是"跳到线"功能,我构建了一个简单的小脚本来做同样的事情。习惯了Gmail的键绑定,我创建了一个输入元素并绑定了" /" input.focus()的关键。然后,您输入一个数字,点击Enter,然后通过window.location.hash跳转到一行代码。这是整个剧本。如果您愿意,可以将它放到GitHub代码页的控制台中:

/*
 * Go to hash location associated with line of code.
 * Assigning line in the if clause is done because parseInt
 * returns falsy if its result is NaN. 
*/ 

function goToLine(line) {
  if (line = parseInt(line)) {
    document.location.hash = "#L" + line;
  }
}

/*
 * Create a text input element. Place it. 
 * Add two keyup listeners: when hitting "Enter",
 * run the goToLine function; second, blur() the input
 * on "Esc" key.
*/

var lineBox = document.createElement("input");
lineBox.setAttribute("style",
             "position: fixed;" +
             "top: 10px;" +
             "right: 10px");
lineBox.setAttribute("type", "text");
document.body.appendChild(lineBox);


lineBox.addEventListener("keyup", function(evt) {
    var key = evt.keyCode || evt.which;

    if (key == 13) {
      goToLine(lineBox.value);
      evt.target.value = "";
      evt.target.blur();
    } else if (key == 27) {
      evt.target.blur();
    }
});

/* 
 * Here is the culprit. Listen for keyup events, and when
 * the key is "/", focus on the input box. Problem: after jumping
 * to a line once, any subsequent attempts populate the input
 * with the "/" character. When listening for keydown, the problem
 * is resolved.
*/

document.addEventListener("keyup", function(evt) {
    var key = evt.keyCode || evt.which;
    if ( key == 191) {
      evt.preventDefault();
      lineBox.focus();
    }
});

问题:在第一次尝试时,一切都按预期工作。点击" /",输入获得焦点,键入数字,点击"输入",跳转到该行并输入失去焦点。在第一个之后的任何时候,当你击中" /"键,键被捕获并放置在文本框中。 但是,在听keydown时这个问题并没有出现 - 这似乎有点违反直觉。

当我向这些听众添加一些日志记录并确定以下内容时,我的能力已达到最终:

  1. 第一次" /"如果keyup事件的currentTargetdocumenttargetdocument.body,则会被按下。
  2. 在输入中键入数字并点击Enter后,文档的activeElementdocument.body
  3. 第二次输入" /"时,keyup事件的currentTarget仍为document,但现在其目标是{{1} } - 即使input不再是输入(并且在点击activeElement时调用了input.blur()。
  4. 但是,在执行相同的流程时({1}}除外,Enter始终为keydown
  5. 我很困惑。这是Chrome中的怪癖吗? (我在39.0.2171.95关于小牛队。)或者这是对一般事件处理方式的一些奇怪见解? (target问题并未出现在Safari中。)

0 个答案:

没有答案