以往 HTML 的 input 輸入框,無法即時反映使用者的輸入內(nèi)容。
onkeyup、onkeydown 事件,無法即時、精確地取得使用者的輸入資料;而 onchange、onblur 事件,要等到失去焦點(diǎn)時,或按下 Enter 時,才會被觸發(fā)。
現(xiàn)在 HTML5 新增的 input 事件,可達(dá)成「立即、精準(zhǔn)地觸發(fā)」,類似 AJAX 功能。唯一的缺點(diǎn),是不支援 IE 瀏覽器,但支援其他各瀏覽器。
如下 html 程式碼,可測試出,input 事件可達(dá)成「立即、精準(zhǔn)地觸發(fā)」;舊有的 change 事件,則需要失去焦點(diǎn)時,或按下 Enter 時,才會被觸發(fā)。
1 <!DOCTYPE html> 2 <html > 3 <head> 4 <script> 5 function myFunc1(input) { 6 document.getElementById("output1").value = input; 7 } 8 9 function myFunc2(input) { 10 document.getElementById("output2").value = input; 11 } 12 </script> 13 </head> 14 <body> 15 <input id="input1" type="text" oninput="myFunc1(this.value)" /> 16 <br /> 17 <input id="input2" type="text" onchange="myFunc2(this.value)" /> 18 <p></p> 19 <output id="output1"></output> 20 <br /> 21 <output id="output2"></output> 22 </body> 23 </html>
進(jìn)一步聯(lián)想,若寫的是: 購物商場、網(wǎng)路書城,若要讓 input 或 textarea 輸入框,能夠「立即、精準(zhǔn)地觸發(fā)」,只要使用 HTML5 的 input 事件,則不必自己寫程式去加入 AJAX 功能,就能輸鬆地達(dá)成需求。
如下 html 程式碼:
1 <!DOCTYPE html> 2 <html > 3 <head> 4 <title>oninput</title> 5 <script> 6 function myFunc1(input) { 7 document.getElementById("output1").value = 8 input * 230; 9 } 10 </script> 11 </head> 12 <body> 13 書名:快快樂樂學(xué)HTML5, <br /> 14 價格:230, 購買數(shù)量: 15 <input id="input1" type="number" step="1" value="0" oninput="myFunc1(this.value)" /> 16 <br /><br /> 17 結(jié)帳金額: 18 <output id="output1"></output> 19 </body> 20 </html>

圖 1 執(zhí)行結(jié)果
HTML5 的 input 事件,主要的缺點(diǎn),是不支援微軟的 IE 瀏覽器,但支援 Chrome、Firefox、Opera、Safari、微軟的 Edge。
因此在網(wǎng)頁裡,引用此事件,對手機(jī)、平板上的操作,並不造成影響。
--------------------------------------------
--------------------------------------------
參考書籍:
[1] HTML5 完美風(fēng)暴(第三版), ch5, 作者:呂高旭
http://www.books.com.tw/products/0010668517
--------------------------------------------
相關(guān)文章:
[1] HTML 事件屬性
http://www.runoob.com/jsref/event-oninput.html
http://www.w3school.com.cn/tags/html_ref_eventattributes.asp
[2] HTML5 input 事件檢測輸入框變化
http://www.rzrgm.cn/luozhihao/p/4649868.html
[3] HTML5 標(biāo)準(zhǔn)事件 oninput 實(shí)現(xiàn)輸入檢測
https://www.fedte.cc/p/604.html
--------------------------------------------
--------------------------------------------
浙公網(wǎng)安備 33010602011771號