
input 中,要輸入資料時,會看到有個藍色外框,這是 focus 效果,focus 有焦點,聚焦的意思,而 blur 英文單字中這是模糊的意思,這樣聯想,就會比較好知道這兩個效果的關聯性。
練習主題
寫一個 input,在點擊後但未輸入資料,在移開後,產生 alert 視窗告知填寫資料。
先寫架構
HTML
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 
 | <!DOCTYPE html><html lang="en">
 <head>
 <meta charset="UTF-8" />
 <meta name="viewport" content="width=device-width, initial-scale=1.0" />
 <title>blur</title>
 </head>
 
 <body>
 <input type="text" class="input" placeholder="請輸入資料" />
 <button class="btn">送出</button>
 
 <script src="js/all.js"></script>
 </body>
 </html>
 
 | 
送出的按紐,盡量習慣用 button
JavaScript
先綁定 .input,並且設定監聽事件。
| 12
 
 | var input = document.querySelector(".input"); input.addEventListener("blur", checkContent, false);
 
 | 
建立函式
| 12
 3
 4
 5
 6
 7
 8
 
 | function checkContent(e) {
 var str = e.target.value;
 if (str == "") {
 
 alert("請輸入資料");
 }
 }
 
 | 
如此,就完成倘若點選表單,沒輸入內容,點選到旁邊的位置,就會跳出 alert 視窗,產生互動。
CodePen: https://codepen.io/hnzxewqw/pen/bGdqXMM