Google Drive(或其他服务)如何捕获自定义搜索框的Ctrl+F或Command+F输入?


How does Google Drive (or other services) capture the Ctrl+F or Command+F input for a custom search box?

是否可以创建一个自定义的"查找"框类似于什么谷歌驱动器按下Command+F或Ctrl+F?我是一个完全的新手,我不知道如何更好地表达这个问题,对不起!

它们捕获document上的keydown事件并阻止默认操作的发生,而是做自己的事情:

document.addEventListener("keydown", function(e) {
    if (e.ctrlKey && (e.which || e.keyCode) == 70) {
        e.preventDefault();
        alert("Search!");
    }
}, false);

生活例子:

document.addEventListener("keydown", function(e) {
    if (e.ctrlKey && (e.which || e.keyCode) == 70) {
        e.preventDefault();
        alert("Search!");
    }
}, false);
<p>Click here to focus the snippet's document, then press Ctrl+F</p>

处理程序接收到的事件对象有一个ctrlKey属性,如果按下ctrl键,该属性将有一个真值。在大多数浏览器上,它也有一个which属性来表示哪个键,但在一些浏览器上它是keyCode,所以在上面我使用了奇怪的强大的||操作符来使用浏览器提供的任何一个。