
input 中,要輸入資料時,會看到有個藍色外框,這是 focus 效果,focus 有焦點,聚焦的意思,而 blur 英文單字中這是模糊的意思,這樣聯想,就會比較好知道這兩個效果的關聯性。
寫一個 input,在點擊後但未輸入資料,在移開後,產生 alert 視窗告知填寫資料。
先寫架構
<!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
先綁定 .input,並且設定監聽事件。
var input = document.querySelector(".input"); //選取到 .input
input.addEventListener("blur", checkContent, false); //建立監聽
建立函式
function checkContent(e) {
  //事件監聽
  var str = e.target.value; //宣告字串在這個事件中,目標為值
  if (str == "") {
    //倘若值是空的,記得是要使用運算判斷
    alert("請輸入資料"); //就跳出 alert
  }
}
如此,就完成倘若點選表單,沒輸入內容,點選到旁邊的位置,就會跳出 alert 視窗,產生互動。
CodePen: https://codepen.io/hnzxewqw/pen/bGdqXMM