Вот задание по JavaScript, которое я пытаюсь решить.
Задача:
- Сделать сетку 4x4 из блоков.
- Ниже расположить кнопку [start], при нажатии на которую текст в ней изменится на [in progress], а ячейки в сетке начнут переворачиваться на 180 градусов по очереди (важно заметить, что анимация следующей ячейки должна начинаться перед тем, как закончится анимация предыдущей).
- После окончания эффектов вывести сообщение об успехе и кнопку снова изменить на [start].
Всю служебную информацию записывать в консоль (старт прогресса / старт анимации ячейки / окончание анимации ячейки / окончание прогресса).
- P.S. эффект для ячеек сетки нужно реализовать на CSS.
- P.S.S. если сделать сетку 4x5, ваш код должен работать.
- P.S.S.S. кроссбраузерность будет плюсом.
Видео с примером реализации: смотреть.
===
Мой старый код(можно не смотреть, тогда я еще почти не знал JavaScript):
*Ответ пользователя wNow шел для этого кода(точнее он все полностью за меня написал, за что ему благодарность).
$(document).ready(function() {
$('button.action').click(function() {
console.log('---PROGRESS START---');
console.log('Cell 1 Animation START');
$("tr.one td:nth-child(1)").addClass("takeover");
window.setTimeout(function() {
console.log('Cell 1 Animation END');
}, 1200);
window.setTimeout(function() {
console.log('Cell 2 Animation START');
$("tr.one td:nth-child(2)").addClass("takeover")
}, 300);
window.setTimeout(function() {
console.log('Cell 2 Animation END');
}, 1500);
window.setTimeout(function() {
console.log('Cell 3 Animation START');
$("tr.one td:nth-child(3)").addClass("takeover")
}, 600);;
window.setTimeout(function() {
console.log('Cell 3 Animation END');
}, 1800);
window.setTimeout(function() {
console.log('Cell 4 Animation START');
$("tr.one td:nth-child(4)").addClass("takeover")
}, 900);
window.setTimeout(function() {
console.log('Cell 4 Animation END');
}, 2100);
window.setTimeout(function() {
console.log('Cell 5 Animation START');
$("tr.two td:nth-child(1)").addClass("takeover")
}, 1200);
window.setTimeout(function() {
console.log('Cell 5 Animation END');
}, 2400);
window.setTimeout(function() {
console.log('Cell 6 Animation START');
$("tr.two td:nth-child(2)").addClass("takeover")
}, 1500);;
window.setTimeout(function() {
console.log('Cell 6 Animation END');
}, 2700);
window.setTimeout(function() {
console.log('Cell 7 Animation START');
$("tr.two td:nth-child(3)").addClass("takeover")
}, 1800);
window.setTimeout(function() {
console.log('Cell 7 Animation END');
}, 3000);
window.setTimeout(function() {
console.log('Cell 8 Animation START');
$("tr.two td:nth-child(4)").addClass("takeover")
}, 2100);
window.setTimeout(function() {
console.log('Cell 8 Animation END');
}, 3300);
window.setTimeout(function() {
console.log('Cell 9 Animation START');
$("tr.three td:nth-child(1)").addClass("takeover")
}, 2400);
window.setTimeout(function() {
console.log('Cell 9 Animation END');
}, 3600);
window.setTimeout(function() {
console.log('Cell 10 Animation START');
$("tr.three td:nth-child(2)").addClass("takeover")
}, 2700);;
window.setTimeout(function() {
console.log('Cell 10 Animation END');
}, 3900);
window.setTimeout(function() {
console.log('Cell 11 Animation START');
$("tr.three td:nth-child(3)").addClass("takeover")
}, 3000);
window.setTimeout(function() {
console.log('Cell 11 Animation END');
}, 4200);
window.setTimeout(function() {
console.log('Cell 12 Animation START');
$("tr.three td:nth-child(4)").addClass("takeover")
}, 3300);
window.setTimeout(function() {
console.log('Cell 12 Animation END');
}, 4500);
window.setTimeout(function() {
console.log('Cell 13 Animation START');
$("tr.four td:nth-child(1)").addClass("takeover")
}, 3600);
window.setTimeout(function() {
console.log('Cell 13 Animation END');
}, 4800);
window.setTimeout(function() {
console.log('Cell 14 Animation START');
$("tr.four td:nth-child(2)").addClass("takeover")
}, 3900);;
window.setTimeout(function() {
console.log('Cell 14 Animation END');
}, 5100);
window.setTimeout(function() {
console.log('Cell 15 Animation START');
$("tr.four td:nth-child(3)").addClass("takeover")
}, 4200);
window.setTimeout(function() {
console.log('Cell 15 Animation END');
}, 5400);
window.setTimeout(function() {
console.log('Cell 16 Animation START');
$("tr.four td:nth-child(4)").addClass("takeover")
}, 4500);
window.setTimeout(function() {
console.log('Cell 16 Animation END');
console.log('---PROGRESS END---');
}, 5700);
});
/*#############################################*/
});
body {
background-color: #212120;
}
/* begin Content */
.content {
margin-top: 200px;
text-align: center;
}
.content table {
margin: auto;
}
.content table tbody tr td {
padding: 20px 40px;
background-color: #4989C7;
color: #fff;
font-size: 30px;
border: 5px solid #212120;
vertical-align: middle;
text-align: center;
}
.content table tbody tr td.takeover {
transform: rotateX(180deg);
transition: 1.2s;
}
.content button {
background-color: #4989C7;
color: #fff;
border: none;
font-size: 20px;
padding: 10px 20px;
margin-top: 20px;
}
.content button:hover {
cursor: pointer;
opacity: 0.9;
}
/* end Content */
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- begin Content -->
<div class="content">
<!-- begin Table -->
<table>
<tbody>
<tr class="one">
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
</tr>
<tr class="two">
<td>5</td>
<td>6</td>
<td>7</td>
<td>8</td>
</tr>
<tr class="three">
<td>9</td>
<td>10</td>
<td>11</td>
<td>12</td>
</tr>
<tr class="four">
<td>13</td>
<td>14</td>
<td>15</td>
<td>16</td>
</tr>
</tbody>
</table>
<!-- end Table -->
<button class="action" type="button"><span>start</span></button>
</div>
<!-- end Content -->
======= Обновлено 30.03.17 =======
Получив знания по JavaScript, написал данный код(по нему и будет вопрос):
'use strict';
function startFliping() {
var score = 0;
screen.innerHTML += '-- PROGRESS START -- <br>';
button.innerHTML = 'in progress';
(function flip() {
var thisScore = score;
var td = tdList[thisScore];
if (thisScore != tdList.length) {
screen.innerHTML += 'Cell ' + (thisScore + 1) + ' Animation START <br>';
screen.scrollTop += screen.offsetHeight; // Добавил скролл, в задании нет, но на видео есть.
td.style.transition = '1s';
td.style.transform = 'rotateX(180deg)';
td.addEventListener('transitionend', function() { // Отслеживаю окончание анимации.
screen.innerHTML += 'Cell ' + (thisScore + 1) + 'Animation END <br>';
screen.scrollTop += screen.offsetHeight;
if (thisScore + 1 == tdList.length) { // Здесь проверка, если подходит, завершаем.
screen.innerHTML += '-- PROGRESS END -- <br>';
alert('sucess');
button.innerHTML = 'start';
screen.scrollTop += screen.offsetHeight;
for (var i = 0, length1 = tdList.length; i < length1; i++) {
tdList[i].style.transition = '0s';
tdList[i].style.transform = 'rotateX(0)';
}
};
});
score++;
setTimeout(flip, 200);
};
return;
})();
};
var flipFlops = document.querySelector('.flipFlops');
var button = flipFlops.querySelector('.button');
var screen = flipFlops.querySelector('.screen');
var tdList = flipFlops.querySelectorAll('td');
button.addEventListener('click', startFliping);
body {
background-color: #f1f1f1;
}
td {
padding: 40px;
color: white;
background: #4289CE;
}
p {
margin: 0;
}
.flipFlops {
text-align: center;
}
table {
margin: auto;
}
.screen {
padding: 10px;
text-align: left;
background: #4289CE;
color: #fff;
width: 380px;
height: 200px;
overflow-y: scroll;
margin: 20px auto;
}
.button {
padding: 10px 50px;
background: #4289CE;
color: #fff;
font-size: 20px;
text-transform: uppercase;
}
.button:hover {
cursor: pointer;
opacity: 0.9;
}
<div class="flipFlops">
<table>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
</tr>
<tr>
<td>5</td>
<td>6</td>
<td>7</td>
<td>8</td>
</tr>
<tr>
<td>9</td>
<td>10</td>
<td>11</td>
<td>12</td>
</tr>
<tr>
<td>13</td>
<td>14</td>
<td>15</td>
<td>16</td>
</tr>
</table>
<div class="screen"></div>
<a class="button">start</a>
</div>
- Использовал рекурсию.
- Добавил комментарии в код.
- Я новичок в js.
Мой вопрос: Первый раз запускаем, все как надо, но если еще запустить(без перезагрузки страницы), то появляется баг, а именно двойные надписи Animation END
и двойной alert
, третий раз запускаем уже три раза и т.д.(хочется чтобы было как при первом запуске). Я долго с этим возился, предполагаю, что проблема с addEventListener('transitionend'
Как поправить не знаю, буду рад получить помощь(хочу узнать из-за чего ошибка и можно ли поправить не меняя сильно код).
Здесь скорее вопрос о нашем понимании русского языка
. Эт как раз вопрос к тому, как вы оформили вопрос. Вам стоит прочитать справку как задавать вопросы. Как новичок, кстати, вас после регистрации должно было о данном разделе уведомить и вы бы после прочтения оформили лучше всё ;-)addEventListener('transitionend...
во внутрь той функции записывать ) Что интересно, после повторного открытия данного вопроса, из поставивших минус людей, только один написал небольшой комментарий здесь, и ни один не написал на мете. Хорошо, что есть и те, кто плюсы поставил. В таком случае награда достается wNow, как единственному кто дал ответ. Получается, не так это и плохо, помочь новичку с одним единственным сообщением.