簡體   English   中英

使用 Javascript,如何檢測按鍵事件而不是用戶在表單字段中鍵入時?

[英]Using Javascript, how can I detect a keypress event but NOT when the user is typing in a form field?

在我的網站上,我想在用戶點擊問號鍵時動態打開我的搜索表單。 我可以使用以下代碼做到這一點:

document.onkeyup = checkKey;
function checkKey(evt) {
    evt = evt || window.event;
    if (evt.keyCode == '191') { // user inputs the "?" key [shift + /]
        // Do something
    }
}

但是,如果用戶只是在評論字段或搜索字段中輸入問號,我不想觸發該操作。 例如,在 Gmail 中,您可以點擊“?” 打開鍵盤快捷鍵覆蓋,但如果您正在撰寫電子郵件並鍵入“?” 快捷方式打不開。

當用戶碰巧在表單字段中鍵入時,如何檢測按鍵事件而不是?

嗅探事件target屬性的tagName可能就足夠了。 下面的內容顯然不是詳盡無遺的——有幾個邊緣情況需要考慮——但這是一個開始。 嘗試在表單元素中輸入 when ,然后在文檔中的其他地方輸入:

 document.onkeyup = checkKey; function checkKey(evt) { const formElements = ['INPUT', 'TEXTAREA', 'SELECT', 'OPTION']; evt = evt || window.event; if (formElements.includes(evt.target.tagName)) { console.log('ignore me!'); } else { console.log('do something!'); } }
 <h1>my form</h1> <form> <label for="name">name</label> <input id="name" name="name" /> <br/> <label for="aboutme">about me</label> <textarea id="aboutme" name="aboutme"></textarea> <br/> <label for="ghostbuster">ghostbuster</label> <select id="ghostbuster" name="ghostbuster"> <option value="winstonzeddmore">Winston Zeddmore</option> <option value="egonspangler">Egon Spangler</option> <option value="petervenkman">Peter Venkman</option> <option value="raystanz">Ray Stanz</option> </select> </form> <p> some text</p>

在 checkKey 函數中,您可以訪問事件對象。 您可以檢查事件的目標以確定如何處理它。 在這種情況下,您可以將示例修改為如下所示:

document.onkeyup = checkKey;
function checkKey(evt) {
    evt = evt || window.event;
    if (evt.target.type === 'input') {
       return;
    }
    if (evt.keyCode == '191') { // user inputs the "?" key [shift + /]
        // Do something
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM