簡體   English   中英

如何在移動瀏覽器上監聽輸入事件?

[英]How do I listen for input events on mobile browsers?

我寫了一個愚蠢的小“網絡應用程序”,它由一個簡單的文本框組成,該文本框可以操作文本並顯示 output。在桌面上按我預期的方式工作,但在移動設備上卻不行(Chrome 和 Safari 在 iOS 上)。 我只是將事件偵聽器添加到輸入,但處理程序似乎沒有被觸發。 我檢查了 caniuse,它似乎兼容,但沒有發現任何關於此的問題,所以我希望這是我在代碼中忽略的東西。

代碼片段:

const input = document.querySelector('#input'); // Yes, that's the input ID.
input.addEventListener('change', clapBack);

鏈接到完整文件:

https://github.com/martellaj/clap-back-generator/blob/master/js/main.js

正如@jam mok所說,手機不支持輸入。 為什么不只使用更改事件?

const input = document.querySelector('#input'); // Yes, that's the input ID.
input.addEventListener('change', clapBack);

對於仍在尋找答案的所有人類: onkeyup()可以解決問題。

因此,上述代碼的解決方案可能如下所示:

const input = document.querySelector('#input'); // Yes, that's the input ID.
input.addEventListener('keyup', clapBack);

當然也可以內聯使用: <input name="inputText" onkeyup="clapBack()">

在2019年進行更新:大多數流行的移動瀏覽器都支持inputchangehttps : //developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event

以下內容使您可以檢測移動瀏覽器上的更改:

const input = document.querySelector('#input'); // Yes, that's the input ID.
input.addEventListener('change', clapBack);

這是一個示例: https : //codepen.io/anon/pen/LwVoWa

而不是使用事件 事件 keypress (keyup, keydown) 事件的代碼屬性,我使用過event 輸入類型事件 更新事件的數據,並向輸入標簽添加了一些限制屬性,以克服移動鍵盤應用程序的“智能”。 這是一個丑陋的 hack,但對我的目的有用。

HTML:

<input type="text" id="inpt" autocapitalize="none" autocomplete="off" autocorrect="off" spellcheck="false" />

記者:

var inpt = document.getElementById('inpt');
inpt.addEventListener('input', do_on_input);

function do_on_input(e) {
  
  if( e.inputType == "insertText"){
    console.log( e.data );
  }
  
  if( e.inputType == "deleteContentBackward"){
    console.log('Backspace');     
  }
  
  if( e.inputType == "insertCompositionText"){
    // without restrictive attribbutes you will need to deal with this type events
  }
  
}

暫無
暫無

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

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