Как можно с помощью js сделать анимацию исчезновения и появления блоков с учётом того, что у блоков "tab" display: none;?
let currentTab = 0 // Текущий таб
showTab(currentTab);
const next = document.querySelector('.next'),
prev = document.querySelector('.prev');
function showTab(n) { // Отвечает за показ текущего таба и показ кнопки "Назад (prev)"
let x = document.querySelectorAll('.tab');
const prev = document.querySelector('.prev');
x[n].style.display = "block";
if (n == 0) {
prev.style.display = "none";
} else {
prev.style.display = "inline";
}
}
next.addEventListener('click', () => { // Логика кнопки "Вперёд (next)" По нажатию на кнопку проверка полей на валидность и смена текущего таба
let x = document.querySelectorAll('.tab');
if (!validateForm()) { // Проверка полей на валидность
return
}
if (currentTab <= 2) { // Смена табов
x[currentTab].style.display = "none";
currentTab = ++currentTab;
x[currentTab].style.display = "block";
}
showTab(currentTab);
step(currentTab);
});
prev.addEventListener('click', () => { // Логика кнопки "Назад (prev)"
let x = document.querySelectorAll('.tab');
x[currentTab].style.display = "none";
currentTab = --currentTab;
x[currentTab].style.display = "block";
showTab(currentTab);
step(currentTab);
});
function step(n) { // Показывает на каком ты сейчас вопросе
var x = document.getElementsByClassName("step");
for (let i = 0; i < x.length; i++) {
x[i].classList.remove("current-step");
}
x[n].classList.add("current-step");
}
function validateForm() {
var x, y, i, valid = true;
x = document.getElementsByClassName("tab");
y = x[currentTab].getElementsByTagName("input");
for (i = 0; i < y.length; i++) {
if (y[i].value == "") {
y[i].className += " invalid";
valid = false;
}
}
//if (valid) {
// document.getElementsByClassName("step")[currentTab].className += " finish";
//}
return valid; // return the valid status
}
* {
box-sizing: border-box;
padding: 0;
margin: 0;
}
body {
font-family: sans-serif;
background-color: #F9F9F9;
}
/*================================================================================================================
==================================================================================================================*/
#regForm {
background-color: #ffffff;
margin: 100px auto;
font-family: Raleway;
padding: 40px;
width: 70%;
min-width: 300px;
}
h1 {
text-align: center;
}
input {
padding: 10px;
width: 100%;
font-size: 17px;
font-family: Raleway;
border: 1px solid #aaaaaa;
}
/* Mark input boxes that gets an error on validation: */
input.invalid {
background-color: #ffdddd;
}
/* Hide all steps by default: */
.tab {
display: none;
}
.tabAnimeOut {
transition: 1s;
opacity: 0;
}
.tabAnimeoutIn {
transition: 1s;
opacity: 0;
}
button {
background-color: #4CAF50;
color: #ffffff;
border: none;
padding: 10px 20px;
font-size: 17px;
font-family: Raleway;
cursor: pointer;
}
button:hover {
opacity: 0.8;
}
#prevBtn {
background-color: #bbbbbb;
}
/* Make circles that indicate the steps of the form: */
.step {
height: 15px;
width: 15px;
margin: 0 2px;
background-color: #bbbbbb;
border: none;
border-radius: 50%;
display: inline-block;
opacity: 0.5;
}
.step.active {
opacity: 1;
}
/* Mark the steps that are finished and valid: */
.step.finish {
background-color: #4CAF50;
}
.current-step{
background-color: blue;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>Document</title>
</head>
<body>
<form id="regForm" action="/action_page.php">
<h1>Register:</h1>
<!-- One "tab" for each step in the form: -->
<div class="tab">Name:
<p><input placeholder="First name..." name="fname"></p>
<p><input placeholder="Last name..." name="lname"></p>
</div>
<div class="tab">Contact Info:
<p><input placeholder="E-mail..." name="email"></p>
<p><input placeholder="Phone..." name="phone"></p>
</div>
<div class="tab">Birthday:
<p><input placeholder="dd" name="dd"></p>
<p><input placeholder="mm" name="nn"></p>
<p><input placeholder="yyyy" name="yyyy"></p>
</div>
<div class="tab">Login Info:
<p><input placeholder="Username..." name="uname"></p>
<p><input placeholder="Password..." name="pword" type="password"></p>
</div>
<div style="overflow:auto;">
<div style="float:right;">
<button type="button" class="prev">Previous</button>
<button type="button" class="next">Next</button>
</div>
</div>
<!-- Circles which indicates the steps of the form: -->
<div style="text-align:center;margin-top:40px;">
<span class="step current-step"></span>
<span class="step"></span>
<span class="step"></span>
<span class="step"></span>
</div>
</form>
<script src="quiz.js"></script>
</body>
</html>
Ответы (2 шт):
Никак.
Анимировать можно только те свойства, для которых существуют исходное, конечное и ПРОМЕЖУТОЧНОЕ состояние.
Например, цвет может быть анимирован (#000000 -> #888888 -> #FFFFFF). Или высота элемента, которая известна и вычислима до того, как будет отрендерен контент (0 -> 34% -> 100%).
А свойство display не может быть анимировано. Сами подумайте каким должно быть промежуточное значение между "block" и "none".
Анимацию исчезновения и появления элементов даже с учётом того, что у них меняется свойство с display: none; на display: block; применить вполне возможно, например путем добавления/удаления дополнительного класса и с помощью правила @keyframes, в котором мы можем указать дополнительное свойство, например opacity, которое будет анимироваться.
let currentTab = 0 // Текущий таб
showTab(currentTab);
const next = document.querySelector('.next'),
prev = document.querySelector('.prev');
function showTab(n) { // Отвечает за показ текущего таба и показ кнопки "Назад (prev)"
let x = document.querySelectorAll('.tab');
const prev = document.querySelector('.prev');
x[n].style.display = "block";
if (n == 0) {
prev.style.display = "none";
} else {
prev.style.display = "inline";
}
}
next.addEventListener('click', () => { // Логика кнопки "Вперёд (next)" По нажатию на кнопку проверка полей на валидность и смена текущего таба
let x = document.querySelectorAll('.tab');
if (!validateForm()) { // Проверка полей на валидность
return
}
if (currentTab <= 2) { // Смена табов
x[currentTab].style.display = "none";
x[currentTab].classList.remove('tab__active');
currentTab = ++currentTab;
//x[currentTab].style.display = "block";
x[currentTab].classList.add('tab__active');
}
showTab(currentTab);
step(currentTab);
});
prev.addEventListener('click', () => { // Логика кнопки "Назад (prev)"
let x = document.querySelectorAll('.tab');
x[currentTab].style.display = "none";
currentTab = --currentTab;
x[currentTab].style.display = "block";
showTab(currentTab);
step(currentTab);
});
function step(n) { // Показывает на каком ты сейчас вопросе
var x = document.getElementsByClassName("step");
for (let i = 0; i < x.length; i++) {
x[i].classList.remove("current-step");
}
x[n].classList.add("current-step");
}
function validateForm() {
var x, y, i, valid = true;
x = document.getElementsByClassName("tab");
y = x[currentTab].getElementsByTagName("input");
for (i = 0; i < y.length; i++) {
if (y[i].value == "") {
y[i].className += " invalid";
valid = false;
}
}
//if (valid) {
// document.getElementsByClassName("step")[currentTab].className += " finish";
//}
return valid; // return the valid status
}
* {
box-sizing: border-box;
padding: 0;
margin: 0;
}
body {
font-family: sans-serif;
background-color: #F9F9F9;
}
/*================================================================================================================
==================================================================================================================*/
#regForm {
background-color: #ffffff;
margin: 100px auto;
font-family: Raleway;
padding: 40px;
width: 70%;
min-width: 300px;
}
h1 {
text-align: center;
}
input {
padding: 10px;
width: 100%;
font-size: 17px;
font-family: Raleway;
border: 1px solid #aaaaaa;
}
/* Mark input boxes that gets an error on validation: */
input.invalid {
background-color: #ffdddd;
}
/* Hide all steps by default: */
.tab {
display: none;
}
.tab__active {
animation: 3s forwards tab;
}
@keyframes tab {
0% {
display: none;
opacity: 0;
}
1% {
display: block;
opacity: 0;
}
100% {
display: block;
opacity: 1;
}
}
.tabAnimeOut {
transition: 1s;
opacity: 0;
}
.tabAnimeoutIn {
transition: 1s;
opacity: 0;
}
button {
background-color: #4CAF50;
color: #ffffff;
border: none;
padding: 10px 20px;
font-size: 17px;
font-family: Raleway;
cursor: pointer;
}
button:hover {
opacity: 0.8;
}
#prevBtn {
background-color: #bbbbbb;
}
/* Make circles that indicate the steps of the form: */
.step {
height: 15px;
width: 15px;
margin: 0 2px;
background-color: #bbbbbb;
border: none;
border-radius: 50%;
display: inline-block;
opacity: 0.5;
}
.step.active {
opacity: 1;
}
/* Mark the steps that are finished and valid: */
.step.finish {
background-color: #4CAF50;
}
.current-step {
background-color: blue;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>Document</title>
</head>
<body>
<form id="regForm" action="/action_page.php">
<h1>Register:</h1>
<!-- One "tab" for each step in the form: -->
<div class="tab">Name:
<p><input placeholder="First name..." name="fname"></p>
<p><input placeholder="Last name..." name="lname"></p>
</div>
<div class="tab">Contact Info:
<p><input placeholder="E-mail..." name="email"></p>
<p><input placeholder="Phone..." name="phone"></p>
</div>
<div class="tab">Birthday:
<p><input placeholder="dd" name="dd"></p>
<p><input placeholder="mm" name="nn"></p>
<p><input placeholder="yyyy" name="yyyy"></p>
</div>
<div class="tab">Login Info:
<p><input placeholder="Username..." name="uname"></p>
<p><input placeholder="Password..." name="pword" type="password"></p>
</div>
<div style="overflow:auto;">
<div style="float:right;">
<button type="button" class="prev">Previous</button>
<button type="button" class="next">Next</button>
</div>
</div>
<!-- Circles which indicates the steps of the form: -->
<div style="text-align:center;margin-top:40px;">
<span class="step current-step"></span>
<span class="step"></span>
<span class="step"></span>
<span class="step"></span>
</div>
</form>
<script src="quiz.js"></script>
</body>
</html>
upd:
let currentTab = 0 // Текущий таб
showTab(currentTab);
const next = document.querySelector('.next'),
prev = document.querySelector('.prev');
function showTab(n) { // Отвечает за показ текущего таба и показ кнопки "Назад (prev)"
let x = document.querySelectorAll('.tab');
const prev = document.querySelector('.prev');
//x[n].style.display = "block";
x[n].classList.add('tab__active');
if (n == 0) {
prev.style.display = "none";
} else {
prev.style.display = "inline";
}
}
next.addEventListener('click', () => { // Логика кнопки "Вперёд (next)" По нажатию на кнопку проверка полей на валидность и смена текущего таба
let x = document.querySelectorAll('.tab');
// if (!validateForm()) { // Проверка полей на валидность
// return
// }
if (currentTab <= 2) { // Смена табов
//x[currentTab].style.display = "none";
x[currentTab].classList.remove('tab__active');
x[currentTab].classList.add('tab__unactive');
currentTab = ++currentTab;
x[currentTab].classList.remove('tab__unactive');
x[currentTab].classList.add('tab__active');
}
showTab(currentTab);
step(currentTab);
});
prev.addEventListener('click', () => { // Логика кнопки "Назад (prev)"
let x = document.querySelectorAll('.tab');
x[currentTab].classList.remove('tab__active');
x[currentTab].classList.add('tab__unactive');
//x[currentTab].style.display = "none";
currentTab = --currentTab;
x[currentTab].classList.remove('tab__unactive');
x[currentTab].classList.add('tab__active');
//x[currentTab].style.display = "block";
showTab(currentTab);
step(currentTab);
});
function step(n) { // Показывает на каком ты сейчас вопросе
var x = document.getElementsByClassName("step");
for (let i = 0; i < x.length; i++) {
x[i].classList.remove("current-step");
}
x[n].classList.add("current-step");
}
function validateForm() {
var x, y, i, valid = true;
x = document.getElementsByClassName("tab");
y = x[currentTab].getElementsByTagName("input");
for (i = 0; i < y.length; i++) {
if (y[i].value == "") {
y[i].className += " invalid";
valid = false;
}
}
//if (valid) {
// document.getElementsByClassName("step")[currentTab].className += " finish";
//}
return valid; // return the valid status
}
* {
box-sizing: border-box;
padding: 0;
margin: 0;
}
body {
font-family: sans-serif;
background-color: #F9F9F9;
}
/*================================================================================================================
==================================================================================================================*/
#regForm {
background-color: #ffffff;
margin: 100px auto;
font-family: Raleway;
padding: 40px;
width: 70%;
min-width: 300px;
}
h1 {
text-align: center;
}
input {
padding: 10px;
width: 100%;
font-size: 17px;
font-family: Raleway;
border: 1px solid #aaaaaa;
}
/* Mark input boxes that gets an error on validation: */
input.invalid {
background-color: #ffdddd;
}
/* Hide all steps by default: */
.tab {
/*display: none;*/
max-height: 0;
overflow: hidden;
}
.tab__unactive {
/*display: none;*/
overflow: hidden;
animation: 2s forwards tabOut;
}
@keyframes tabOut {
0% {
/*display: block;*/
max-height: 500px;
opacity: 1;
}
99% {
/*display: block;*/
max-height: 0;
opacity: 0;
}
100% {
/*display: none;*/
max-height: 0;
opacity: 0;
}
}
.tab__active {
/*display:block;*/
animation: 4s forwards tabIn;
}
@keyframes tabIn {
0% {
display: none;
max-height: 0;
opacity: 0;
}
50% {
display: none;
max-height: 0;
opacity: 0;
}
50.1% {
display: block;
max-height: 0;
opacity: 0;
}
100% {
display: block;
max-height: 500px;
opacity: 1;
}
}
button {
background-color: #4CAF50;
color: #ffffff;
border: none;
padding: 10px 20px;
font-size: 17px;
font-family: Raleway;
cursor: pointer;
}
button:hover {
opacity: 0.8;
}
#prevBtn {
background-color: #bbbbbb;
}
/* Make circles that indicate the steps of the form: */
.step {
height: 15px;
width: 15px;
margin: 0 2px;
background-color: #bbbbbb;
border: none;
border-radius: 50%;
display: inline-block;
opacity: 0.5;
}
.step.active {
opacity: 1;
}
/* Mark the steps that are finished and valid: */
.step.finish {
background-color: #4CAF50;
}
.current-step {
background-color: blue;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>Document</title>
</head>
<body>
<form id="regForm" action="/action_page.php">
<h1>Register:</h1>
<!-- One "tab" for each step in the form: -->
<div class="tab">Name:
<p><input placeholder="First name..." name="fname"></p>
<p><input placeholder="Last name..." name="lname"></p>
</div>
<div class="tab">Contact Info:
<p><input placeholder="E-mail..." name="email"></p>
<p><input placeholder="Phone..." name="phone"></p>
</div>
<div class="tab">Birthday:
<p><input placeholder="dd" name="dd"></p>
<p><input placeholder="mm" name="nn"></p>
<p><input placeholder="yyyy" name="yyyy"></p>
</div>
<div class="tab">Login Info:
<p><input placeholder="Username..." name="uname"></p>
<p><input placeholder="Password..." name="pword" type="password"></p>
</div>
<div style="overflow:auto;">
<div style="float:right;">
<button type="button" class="prev">Previous</button>
<button type="button" class="next">Next</button>
</div>
</div>
<!-- Circles which indicates the steps of the form: -->
<div style="text-align:center;margin-top:40px;">
<span class="step current-step"></span>
<span class="step"></span>
<span class="step"></span>
<span class="step"></span>
</div>
</form>
<script src="quiz.js"></script>
</body>
</html>