gpt4 book ai didi

javascript - 在我的案例中如何启动 css 动画?

转载 作者:行者123 更新时间:2023-11-30 12:49:31 24 4
gpt4 key购买 nike

我正在尝试使用 javascript 在我的应用程序中启动一个 css 动画。

我有这样的东西。

#ball{
position:absolute;
animation-name:myfirst;
animation-duration:5s;
animation-timing-function:linear;

animation-iteration-count:infinite;
animation-direction:alternate;
animation-play-state:running;
/* Safari and Chrome: */
-webkit-animation-name:myfirst;
-webkit-animation-duration:2s;
-webkit-animation-timing-function:linear;

-webkit-animation-iteration-count:1;
-webkit-animation-direction:default;
-webkit-animation-play-state:running;
}


.stage2{
position:absolute;
animation-name:mySecond;
animation-duration:5s;
animation-timing-function:linear;

animation-iteration-count:infinite;
animation-direction:alternate;
animation-play-state:running;
/* Safari and Chrome: */
-webkit-animation-name:myfirst;
-webkit-animation-duration:2s;
-webkit-animation-timing-function:linear;

-webkit-animation-iteration-count:1;
-webkit-animation-direction:default;
-webkit-animation-play-state:running;
}

@-webkit-keyframes myfirst /* Safari and Chrome */
{
0% {left:2%; top:47%;}
20% {left:16%; top:47%;}
40% {left:16%; top:58%;}
60% {left:-10%; top:58%;}
80% {left:-10%; top:67%;}
100% {left:12%; top:67%;}
}

@-webkit-keyframes mySecond /* Safari and Chrome */
{
0% {background:red; left:2%; top:25%;}
20% {background:yellow; left:16%; top:25%;}
40% {background:blue; left:16%; top:35%;}
60% {background:green; left:0; top:35%;}
80% {background:red; left:0; top:45%;}
100% {background:red; left:12%; top:45%;}
}

html

<img id='ball' src='test.png' />
<a href='#' >click </a>

我想让我的 img 在用户单击按钮时启动另一个动画。

js

$('#ball').on('animationend mozanimationend webkitAnimationEnd oAnimationEnd    
msanimationend',function(){
//first animation ended // works perfect
$(this).hide()
})

$('a').on('click', function(){
$('#ball').show().addClass('stage2')
})

好像不行。谁能帮我解决这个问题?非常感谢!

最佳答案

这是一个 CSS 问题。元素 .stage2 具有以下属性:

-webkit-animation-name:myfirst;

这是错误的,因为您为两个动画使用了相同的动画名称。

应该是:

-webkit-animation-name:mySecond;

除此之外,最好使用动画速记:

#ball {
position:absolute;
padding:10px;
-webkit-animation:myfirst 2s linear 1;
}
#ball.stage2 {
-webkit-animation:mySecond 2s linear 1;
}

(对于-webkit以外的浏览器,您还应该添加前缀和@keyframes。)

除了这些错误之外,还有一个特殊性冲突,因为第一个动画会无限播放并在添加类时覆盖第二个动画。我通过将 id 添加到第二个选择器 #ball.stage2 来解决此问题 - 从而使其更加具体。这将现在导致它在添加类时覆盖第一个动画。

另外,作为 Arun P Johny points out , jQuery 中也有一个换行符。删除它,并修复 JS 问题,它应该可以工作。

UPDATED EXAMPLE HERE - (仅限-webkit - 我没有添加其他前缀)

您可以看出第二个动画正在运行,因为背景颜色现在发生了变化。

关于javascript - 在我的案例中如何启动 css 动画?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21447667/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com