[英]trigger animation using Javascript when required fields are filled
当用户尝试单击提交按钮时,我想实现 function,当用户完成所有必填字段时,有一个条件,该按钮将被动画化,表示成功。 第二个是当用户没有填写必填字段时,按钮不会做任何 animation。
我在codepen上上传了它:
https://codepen.io/amrlamin/pen/dyyQyvj
这是js代码:
const button = document.querySelector('.button');
const submit = document.querySelector('.submit');
function toggleClass() {
this.classList.toggle('active');
}
function addClass() {
this.classList.add('finished');
}
document.addEventListener('button', function(){
const name = document.getElementById('firstname').value;
if (name != '') {
button.addEventListener('click', toggleClass);
button.addEventListener('transitionend', toggleClass);
button.addEventListener('transitionend', addClass);
} else {
alert('error');
}
});
但是,我很困惑,需要帮助。 目前,如果用户没有像我想要的那样填写输入字段,则会触发 required 属性。 问题是当用户已经填写了输入时,animation 将不会加载。
1. “......当用户尝试点击提交按钮时,有一个条件是用户完成了所有必填字段,按钮将被动画表示成功”
您目前看到的是对 HTML 标准的验证。 默认情况下,当字段为必填且没有输入时,浏览器会显示一条消息。
如果假设您想触发您自己的自定义 animation,您可以使用HTML 元素上的novalidate
属性并编写您自己的验证。 为此,您还必须捕获提交事件,如本答案的下一部分所述。
2. “...问题是当用户已经填写了输入时,animation 将无法加载。”
所以在这种情况下,这是快乐的流程。 animation 未显示的原因是表单将成功。
如果您希望在该事件之前发生某些事情,例如发生一些自定义表单验证,您将必须捕获表单提交事件。 此堆栈溢出答案中解释了一个示例。 (我将在下一节的代码示例中使用此堆栈溢出答案的示例。)
捕获事件后,您可以在“提交”该事件之前验证或修改类。
例子:
换句话说,实际示例: https://codepen.io/studiospindle/pen/qBBLXee
/* note that in the HTML the form has the 'novalidate' attribute */
const form = document.getElementById('form');
const button = document.querySelector('.button');
const submit = document.querySelector('.submit');
function toggleClass() {
this.classList.toggle('active');
}
function addClass() {
this.classList.add('finished');
}
function processForm(event) {
/* prevent the default submit action from happening */
if (event.preventDefault) event.preventDefault();
/* you won't have to check for the input element independently, you can check the event.target for this */
const firstNameInput = event.target['firstname'];
if (firstNameInput.value && firstNameInput.value != undefined) {
button.addEventListener('click', toggleClass);
button.addEventListener('transitionend', toggleClass);
button.addEventListener('transitionend', addClass);
/* manually set a timer to wait for the transition to finish */
setTimeout(function(){
/* Here you can submit the form again */
form.submit();
}, 5000); // 5000 milliseconds = 5 seconds
} else {
firstNameInput.classList.add('error');
}
/* You must return false to prevent the default form behavior */
return false;
}
/*
* Check if the form has an attachEvent method,
* if yes, then execute our own processForm method
*/
if (form.attachEvent) {
form.attachEvent("submit", processForm);
} else {
form.addEventListener("submit", processForm);
}
与您的示例不同的主要概念是使用表单的提交事件而不是按钮。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.