Try   HackMD

10. 文字欄位事件:focus、blur 的關係

什麼是 focus?

  1. 當 user 將游標移動到欄位時,並且點擊準備要輸入的動作
    即為:focus

    ex:

    Image Not Showing Possible Reasons
    • The image file may be corrupted
    • The server hosting the image is unavailable
    • The image path is incorrect
    • The image format is not supported
    Learn More →

    欄位有顯示被點擊的狀態 這就是觸發了 focus event


製作 blur 事件:

  1. 產生兩個 input text 欄位標籤內容:
// HTML:

    <h1>文字欄位:blur、focus 的關係:</h1>
    <p>
        欄位1: <input class="textboxone" type="text">
    </p>
    <p>
        欄位2: <input class="textboxtwo" type="text">
    </p>
  1. 使用選擇器指定監聽 textboxone、two,且以'blur'為條件:
// JavaScript:

var textboxone = document.querySelector('.textboxone');
var textboxtwo = document.querySelector('.textboxtwo');


textboxone.addEventListener('blur', function (e) {
    if (e.target.value == '') {
        console.log('欄位1不可為空值');
    }
}, false)

textboxtwo.addEventListener('blur', function (e) {
    if (e.target.value == '') {
        console.log('此欄位2不可為空值');
    }
}, false)
當游標點擊欄位會產生 - focus 事件
此時若不輸入任何內容(value),若為空在點擊任何地方則反饋內容

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

tags: JavaScript - event 事件