[js笔记] focus和blur事件之表单验证

  • focus 当一个元素获得焦点时,这个DOM节点会触发focus事件
  • blur 当一个元素失去焦点时,这个DOM节点会触发blur事件


<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>Insert title heretitle>
head>
<body>
    <form method="post" action="#">
        <label for="username">Create a userName:label> <input type="text"
            id="username" />
        <div id="feedback">div>

        <label for="password">Create a password:label> <input
            type="password" /> <br> <input type="submit" value="Sign up!" />
    form>

<script type="text/javascript">
    function checkUsername() {
        var username = el.value;
        if (username.length < 5) {
            elMsg.className = 'Warning';
            elMsg.textContent = 'Not long enough, yet...';
        } else {
            elMsg.textContent = '';
        }
    }

    function tipUsername() {
        elMsg.className = 'tip';
        elMsg.innerHTML = 'Username must be at least 5 characters';
    }

    var el = document.getElementById('username');

    var elMsg = document.getElementById('feedback');
    // focus事件,节点获得焦点时被触发
    el.addEventListener('focus', tipUsername, false);
    // blur事件,节点失去焦点时被触发
    el.addEventListener('blur', checkUsername, false);
script>
body>
html>

你可能感兴趣的:(【编程语言】➣,js)