zoukankan      html  css  js  c++  java
  • HTML5 新增的 input 事件

    以往 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
    --------------------------------------------
    --------------------------------------------

  • 相关阅读:
    MySQL实现嵌套集合模型
    Go项目结构和模块导入
    sqlalchemy(二)高级用法
    sqlalchemy(一)基本操作
    K-均值聚类算法
    回归
    logistic回归
    Android隐藏状态栏、导航栏
    Android监听返回键、Home键+再按一次返回键退出应用
    PDFMate PDF Converter Pro
  • 原文地址:https://www.cnblogs.com/WizardWu/p/8902304.html
Copyright © 2011-2022 走看看