HTML5 form表单事件

188 阅读1分钟
<style>
  form{
    width: 100%;
    max-width: 640px;
    min-width: 320px;
    margin: 0 auto;
    font-family: "Microsoft Yahei";
    font-size: 20px;
  }
  input{
    display: block;
    width: 100%;
    height: 30px;
    margin: 10px 0;
  }
</style>
<form action="">
  <fieldset>

    <!-- 表单标题 -->
    <legend>表单属性</legend>

    <!-- 邮箱 -->
    <label for="email">
      邮箱: <input type="email" name="email" id="email">
    </label>

    <!-- 文本框 -->
    <label for="text">
      文本框: <input type="text" name="text" id="text">
    </label>

    <input type="submit" value="提交">

  </fieldset>
</form>

<script>

  // 表单事件:
  // oninput 当用户输入的时候
  var email = document.getElementById('email');
  var text = document.getElementById('text');
  email.oninput = function () {
    text.value = email.value
  }

  // oninvalid 当验证不通过时触发
  email.oninvalid = function () {
    this.setCustomValidity('亲,请输入正确的邮箱!')
  }
</script>