首頁 >web前端 >js教程 >如何在不失去焦點的情況下追蹤即時輸入變化?

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

Susan Sarandon
Susan Sarandon原創
2024-11-15 12:34:02557瀏覽

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中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn