首頁 > web前端 > js教程 > 主體

如何在不失去焦點的情況下追蹤即時輸入變化?

Susan Sarandon
發布: 2024-11-15 12:34:02
原創
459 人瀏覽過

How Can I Track Real-time Input Changes Without Losing Focus?

Tracking Input Changes in Real-time Using 'onchange' without Losing Focus

Input controls with the "text" type typically trigger the "onchange" event only when the user leaves (blurs) the field. This limitation can be frustrating when tracking changes as the user types.

Fortunately, modern browsers offer a better solution: "oninput." This event listener provides a real-time update of the textfield's content, eliminating the need to lose focus. For maximum compatibility, it's advisable to use both "oninput" and "onpropertychange" for IE support.

An example illustrating this approach:

const source = document.getElementById('source');
const result = document.getElementById('result');

const inputHandler = function(e) {
  result.innerText = e.target.value;
}

source.addEventListener('input', inputHandler);
source.addEventListener('propertychange', inputHandler); // for IE8
登入後複製

Additional Notes for Browser Compatibility:

  • "oninput" is supported in all major browsers, including mobile browsers.
  • IE8 and below require the "onpropertychange" event.
  • "onchange" is not appropriate for tracking as-you-type changes due to its delay after losing focus.

以上是如何在不失去焦點的情況下追蹤即時輸入變化?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板