所以,在得知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
时这个问题并没有出现 - 这似乎有点违反直觉。
当我向这些听众添加一些日志记录并确定以下内容时,我的能力已达到最终:
keyup
事件的currentTarget
为document
,target
为document.body
,则会被按下。Enter
后,文档的activeElement
为document.body
。keyup
事件的currentTarget
仍为document
,但现在其目标是{{1} } - 即使input
不再是输入(并且在点击activeElement
时调用了input.blur()。Enter
始终为keydown
。我很困惑。这是Chrome中的怪癖吗? (我在39.0.2171.95关于小牛队。)或者这是对一般事件处理方式的一些奇怪见解? (target
问题并未出现在Safari中。)