WizardWu 編程網

一位台灣的工程師,接觸 .NET 逾十年,近年研究 SQL Server、Performance Tuning、手機應用

博客园 首页 新随笔 联系 订阅 管理

以往 HTML 的 input 輸入框,無法即時反映使用者的輸入內容。
onkeyup、onkeydown 事件,無法即時、精確地取得使用者的輸入資料;而 onchange、onblur 事件,要等到失去焦點時,或按下 Enter 時,才會被觸發。

現在 HTML5 新增的 input 事件,可達成「立即、精準地觸發」,類似 AJAX 功能。唯一的缺點,是不支援 IE 瀏覽器,但支援其他各瀏覽器。

如下 html 程式碼,可測試出,input 事件可達成「立即、精準地觸發」;舊有的 change 事件,則需要失去焦點時,或按下 Enter 時,才會被觸發。

 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>
oninput、onchange 比較


進一步聯想,若寫的是: 購物商場、網路書城,若要讓 input 或 textarea 輸入框,能夠「立即、精準地觸發」,只要使用 HTML5 的 input 事件,則不必自己寫程式去加入 AJAX 功能,就能輸鬆地達成需求。

如下 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     書名:快快樂樂學HTML5, <br />
14     價格:230, 購買數量:
15     <input id="input1" type="number" step="1" value="0" oninput="myFunc1(this.value)" />
16     <br /><br />
17     結帳金額:
18     <output id="output1"></output>
19 </body>
20 </html>

 


圖 1 執行結果


HTML5 的 input 事件,主要的缺點,是不支援微軟的 IE 瀏覽器,但支援 Chrome、Firefox、Opera、Safari、微軟的 Edge。
因此在網頁裡,引用此事件,對手機、平板上的操作,並不造成影響。
--------------------------------------------
--------------------------------------------
參考書籍:

[1] HTML5 完美風暴(第三版), ch5, 作者:呂高旭
http://www.books.com.tw/products/0010668517
--------------------------------------------
相關文章:

[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.cnblogs.com/luozhihao/p/4649868.html

[3] HTML5 标准事件 oninput 实现输入检测
https://www.fedte.cc/p/604.html
--------------------------------------------
--------------------------------------------

 

posted on 2018-04-21 17:21  WizardWu  阅读(2760)  评论(0编辑  收藏  举报