Как запустить по кнопке бесконечную анимацию?
Как по клику на кнопку начать анимацию элементов по очереди, и чтобы она повторялась бесконечно?
Анимация должна быть следующая:
первый элемент (красный квадрат) передвинулся полностью,
когда первый элемент передвинулся полностью, через короткую паузу второй элемент (зеленый) передвинулся,
длинная пауза,
после длинной паузы второй элемент вернулся на место,
когда второй элемент вернулся на место, через короткую паузу первый элемент вернулся на место
длинная пауза, и т.д. всё повторяется
$("button").click(function {
function sam() {
$(".box_one").animate({
left: '200px'
}, 3000, 'linear', sam);
$(".box_two").animate({
left: '400px'
}, 3000, 'linear', sam);
}
sam();
});
.box_one {
position: absolute;
top: 40px;
width: 50px;
height: 50px;
background-color: red;
left: 0;
}
.box_two {
position: absolute;
top: 100px;
width: 50px;
height: 50px;
background-color: green;
left: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="active">Включить анимацию</button>
<div class="box_one"></div>
<div class="box_two"></div>
Ответы (1 шт):
Автор решения: Denis640Kb
→ Ссылка
Дополнение с изменениями автора:
function moove1(){
$(".box_one").animate({
left: '200px'
}, 3000, 'linear');
setTimeout(function () {
moove2();
}, 4000);
}
function moove2(){
$(".box_two").animate({
left: '400px'
}, 3000, 'linear');
setTimeout(function () {
moove3();
}, 4000);
}
function moove3(){
$(".box_two").animate({
left: '0px'
}, 3000, 'linear');
setTimeout(function () {
moove4();
}, 4000);
}
function moove4(){
$(".box_one").animate({
left: '0px'
}, 3000, 'linear');
setTimeout(function () {
moove1();
}, 7000);
}
$("button").on('click', function() {
function func() {
setTimeout(function () {
moove1();
}, 2000);
}
func();
});
.box_one {
position: absolute;
top: 40px;
width: 50px;
height: 50px;
background-color: red;
left: 0;
}
.box_two {
position: absolute;
top: 100px;
width: 50px;
height: 50px;
background-color: green;
left: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="active">Включить анимацию</button>
<div class="box_one"></div>
<div class="box_two"></div>
Если сразу перемещать.
$("button").on('click', function() {
function sam() {
$(".box_one").animate({
left: '200px'
}, 3000, 'linear', sam);
$(".box_two").animate({
left: '400px'
}, 3000, 'linear', sam);
$(".box_one").animate({
left: '0px'
}, 3000, 'linear', sam);
$(".box_two").animate({
left: '0px'
}, 3000, 'linear', sam);
}
setTimeout(sam(), 1000);
});
.box_one {
position: absolute;
top: 40px;
width: 50px;
height: 50px;
background-color: red;
left: 0;
}
.box_two {
position: absolute;
top: 100px;
width: 50px;
height: 50px;
background-color: green;
left: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="active">Включить анимацию</button>
<div class="box_one"></div>
<div class="box_two"></div>