css 当提交输入被点击并且Javascript上的输入为空时,我如何在我的HTML表单上添加动画?

qmelpv7a  于 2022-11-19  发布在  Java
关注(0)|答案(1)|浏览(123)

基本上,我正在编写一个Javascript代码,验证表单是否为空,因此如果一个输入为空,它将从Animate.css库添加一个动画。如果两个输入为空,两个都将制作摇动动画,如果整个表单为空,它将摇动。
我尝试了一个全局函数,它带有添加类的条件,但它不起作用。
这是我的表格:

<form action="" id="form">
  <label for="name">Name</label>
  <input
    type="text"
    placeholder="Name"
    id="name"
    minlength="3"
    required
  />
  <br />
  <label for="email">Email</label>
  <input type="email" placeholder="Emai" id="email" required />
  <br />
  <label for="subject">Subject</label>
  <input
    type="text"
    placeholder="Subject"
    id="subject"
    minlength="3"
    required
  />
  <br />
  <label for="message">Message</label>
  <textarea
    name="message"
    id="message"
    minlength="5"
    placeholder="Message"
    required
    style="resize: none; height: 200px"
  ></textarea>
  <br />
  <button type="submit" class="paper-btn" id="submit">
    Send message
  </button>
</form>

Javascript语言:

(function () {
  var form = document.getElementById("form"),
    name = form.name,
    email = form.email,
    subject = form.subject;
  message = form.message;

  function validateName(e) {
    if (name.value == "" || name.value == null) {
      form.classList.add("animate__animated");
      name.classList.add("animate__shakeX");
      e.preventDefaul();
    } else {
      console.log("error");
    }
  }
  function validateEmail(e) {
    if (email.value == "" || email.value == null) {
      email.classList.add("animate__animated");
      email.classList.add("animate__shakeX");
      e.preventDefaul();
    }
  }

  function validateSubject(e) {
    if (subject.value == "" || subject.value == null) {
      subject.classList.add("animate__animated");
      subject.classList.add("animate__shakeX");
      e.preventDefaul();
    }
  }

  function validateMessage(e) {
    if (subject.value == "" || subject.value == null) {
      message.classList.add("animate__animated");
      message.classList.add("animate__shakeX");
      e.preventDefaul();
    }
  }

  function validateForm(e) {
    validateName(e);
    validateEmail(e);
    validateSubject(e);
    validateMessage(e);
  }
  form.addEventListener("submit", validateForm);
});
oknrviil

oknrviil1#

我认为您只需要调用函数。

(function() {
      var name = document.getElementById("name");
    
      if (name.value == "" || name.value == null) {
        name.classList.add("animate__animated");
        name.classList.add("animate__shakeX"); 
      }
   })();

相关问题