Я работаю над анимацией, я хочу, чтобы 4 элемента казались плавающими независимо друг от друга, для этого я использую одну и ту же анимацию для всех 4 элементов, но использую animation-delay
, чтобы убедиться, что они плавают независимо друг от друга. Проблема заключается в том, что эта анимация происходит внутри элемента, который скрыт при загрузке страницы, и когда этот элемент становится видимым, вы можете увидеть, что происходит задержка анимации. Можно ли запустить анимацию, когда содержащий элемент все еще скрыт, чтобы не было видно задержки? В противном случае, как лучше всего заставить их плавать независимо друг от друга, не слишком усложняя CSS?
$(function() {
$('button').click(function(e) {
e.preventDefault();
$('.scene.one').hide();
$('.scene.two').fadeIn(500);
});
});
.scenes {
height:150px;
width:300px;
border:1px solid black;
}
h1 {
margin:0;
}
p {
margin-bottom:0;
font-size:12px;
}
.scene {
position:relative;
height:100%;
width:100%;
text-align:center;
display:none;
}
.scene-container {
position:absolute;
top:50%;
left:50%;
transform:translateX(-50%) translateY(-50%);
}
.scene.one {
display:block;
}
.float {
display:inline-block;
width:25px;
height:25px;
background:black;
animation-duration: 3s;
animation-iteration-count: infinite;
animation-timing-function: ease-in-out;
}
.animated .float {
animation-name:floating;
}
.float:nth-child(2) {
animation-delay:.5s;
}
.float:nth-child(3) {
animation-delay:1.5s;
}
.float:nth-child(4) {
animation-delay:1s;
}
@keyframes floating {
from { transform: translate(0, 0px); }
65% { transform: translate(0, 15px); }
to { transform: translate(0, -0px); }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="scenes">
<div class="scene one">
<div class="scene-container">
<h1>WELCOME</h1>
<button>Next scene</button>
<p>(Animation delay is still visible even if you wait 2 seconds before clicking)</p>
</div>
</div>
<div class="scene two">
<div class="scene-container">
<div class="float-container animated">
<div class="float"></div>
<div class="float"></div>
<div class="float"></div>
<div class="float"></div>
</div>
</div>
</div>
</div>
2 ответа
Для этого можно использовать отрицательные задержки.
Я установил их с помощью calc, чтобы прояснить логику, но вы также можете использовать рассчитанное значение.
Любое значение, которое после деления на продолжительность анимации дает такое же напоминание, сохранит визуальный эффект неизменным.
$(function() {
$('button').click(function(e) {
e.preventDefault();
$('.scene.one').hide();
$('.scene.two').fadeIn(500);
});
});
.scenes {
height:150px;
width:300px;
border:1px solid black;
}
h1 {
margin:0;
}
p {
margin-bottom:0;
font-size:12px;
}
.scene {
position:relative;
height:100%;
width:100%;
text-align:center;
display:none;
}
.scene-container {
position:absolute;
top:50%;
left:50%;
transform:translateX(-50%) translateY(-50%);
}
.scene.one {
display:block;
}
.float {
display:inline-block;
width:25px;
height:25px;
background:black;
animation-duration: 3s;
animation-iteration-count: infinite;
animation-timing-function: ease-in-out;
}
.animated .float {
animation-name:floating;
}
.float:nth-child(2) {
animation-delay:calc(.5s - 3s);
}
.float:nth-child(3) {
animation-delay:calc(1.5s - 3s);
}
.float:nth-child(4) {
animation-delay:calc(1s - 3s);
}
@keyframes floating {
from { transform: translate(0, 0px); }
65% { transform: translate(0, 15px); }
to { transform: translate(0, -0px); }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="scenes">
<div class="scene one">
<div class="scene-container">
<h1>WELCOME</h1>
<button>Next scene</button>
<p>(Animation delay is still visible even if you wait 2 seconds before clicking)</p>
</div>
</div>
<div class="scene two">
<div class="scene-container">
<div class="float-container animated">
<div class="float"></div>
<div class="float"></div>
<div class="float"></div>
<div class="float"></div>
</div>
</div>
</div>
</div>
Если вы решите использовать visibility: visible
и visibility: hidden
вместо display
, то вы можете анимировать элементы до того, как они будут видны пользователю. К сожалению, это означает, что вы не сможете получить эффект затухания (поскольку он работает специально с display
), но если это необязательно, это может быть для вас жизнеспособным решением:
$(function() {
$('button').click(function(e) {
e.preventDefault();
$('.scene.one').css('display', 'none');
$('.scene.two').css('visibility', 'visible');
});
});
.scenes {
height: 150px;
width: 300px;
border: 1px solid black;
}
h1 {
margin: 0;
}
p {
margin-bottom: 0;
font-size: 12px;
}
.scene {
position: relative;
height: 100%;
width: 100%;
text-align: center;
visibility: hidden;
}
.scene-container {
position: absolute;
top: 50%;
left: 50%;
transform: translateX(-50%) translateY(-50%);
}
.scene.one {
visibility: visible;
}
.float {
display: inline-block;
width: 25px;
height: 25px;
background: black;
animation-duration: 3s;
animation-iteration-count: infinite;
animation-timing-function: ease-in-out;
}
.animated .float {
animation-name: floating;
}
.float:nth-child(2) {
animation-delay: .5s;
}
.float:nth-child(3) {
animation-delay: 1.5s;
}
.float:nth-child(4) {
animation-delay: 1s;
}
@keyframes floating {
from {
transform: translate(0, 0px);
}
65% {
transform: translate(0, 15px);
}
to {
transform: translate(0, -0px);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="scenes">
<div class="scene one">
<div class="scene-container">
<h1>WELCOME</h1>
<button>Next scene</button>
<p>(Wait 2 seconds before clicking)</p>
</div>
</div>
<div class="scene two">
<div class="scene-container">
<div class="float-container animated">
<div class="float"></div>
<div class="float"></div>
<div class="float"></div>
<div class="float"></div>
</div>
</div>
</div>
</div>
Похожие вопросы
Новые вопросы
jquery
jQuery - это библиотека JavaScript, рассмотрите возможность добавления тега JavaScript. jQuery - это популярная кросс-браузерная библиотека JavaScript, которая облегчает прохождение Document Object Model (DOM), обработку событий, анимацию и взаимодействие AJAX, сводя к минимуму расхождения между браузерами. Вопрос с тегом jQuery должен быть связан с jQuery, поэтому jQuery должен использоваться в рассматриваемом коде, и в вопросе должны быть как минимум элементы, связанные с использованием jQuery.