[英]multiple css animations per element doesn't work in Chrome
我正在嘗試為.circle
元素設置動畫。 它應該會增長,然后在一秒后縮小。 所以我為一個元素聲明了 2 個 css 動畫。 在 Firefox 中它運行良好,但在 Chrome 中則不然。
Can-i-use顯示 Chrome 中的animations
css 規則也應該有效。
完整源代碼:
*, *::before, *::after { box-sizing: border-box; } @keyframes one { 100% { width: 5000px; height: 5000px; } } @keyframes two { 100% { width: 0px; height: 0px; } } .container { position: fixed; top: 0; left: 0; width: 100%; height: 100%; display: flex; justify-content: center; align-items: center; background-color: lightsalmon; } .circle { position: absolute; height: 0px; width: 0px; border-radius: 50%; background-color: lightgreen; /** If declare only one animation, then it will work in Chrome */ animation: one ease 1s alternate 1 paused, two ease 1s alternate 1 paused; animation-fill-mode: forwards; }
<div class="container"> <div class="circle"></div> </div> <script> var circle = document.querySelector(".circle"); circle.style.animationPlayState = "running, paused"; setTimeout(() => { circle.style.animationPlayState = "paused, running"; }, 1000); </script>
因此,正如其中一條評論所說,您可以使用單個動畫來完成此操作。 在編碼時,您應該始終嘗試使用語義化的、有意義的名稱,因此我將動畫命名為“ grow-shrink
而不僅僅是one
.
*,
::before,
::after {
box-sizing: border-box;
}
@keyframes grow-shrink {
50% {
width: 5000px;
height: 5000px;
}
}
.container {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
background-color: lightsalmon;
}
.circle {
position: absolute;
height: 0;
width: 0;
border-radius: 50%;
background-color: lightgreen;
animation: grow-shrink 2s;
}
您不需要任何 JavaScript 來執行此操作,也不需要.circle
上的z-index
屬性。 我將您的動畫持續時間更改為2s
而不是1s
2s
因為它正在執行您最初擁有的兩個1s
2s
動畫的工作。 animation-timing-function
初始值已經是ease
,所以我刪除了它,因為它是多余的。 您也不需要alternate
值。
如果您將animation
值中的1
后alternate
為animation-iteration-count
的值,那么可以安全地將其刪除,因為該屬性的初始值已經是1
。 如果你的意思是它的1s
延時的成長動畫開始播放,然后又1秒延時的收縮開始,只是忘了單位,那么你將不得不讓我知道,我會告訴你如何修改它這樣做。 您可以輕松地為動畫開始添加1s
延遲,但如果您使用此解決方案,則必須以不同的方式延遲收縮。
在這里你可以看到它的Codepen 工作。
🚧編輯:解決方案#2 🚧
或者,如果您想了解如何使用您的方法完成此操作(盡管我不建議在此特定動畫中使用它),以下是我在 Chrome(以及所有其他主要瀏覽器)中使用您的示例后的 CSS 代碼:
*,
*::before,
*::after {
box-sizing: border-box;
}
@keyframes grow {
0% {
height: 0;
width: 0;
}
100% {
height: 5000px;
width: 5000px;
}
}
@keyframes shrink {
0% {
height: 5000px;
width: 5000px;
}
100% {
height: 0;
width: 0;
}
}
.container {
align-items: center;
background-color: lightsalmon;
display: flex;
height: 100%;
justify-content: center;
left: 0;
position: fixed;
top: 0;
width: 100%;
}
.circle {
animation:
grow 1s ease-in forwards paused,
shrink 1s ease-out 1s forwards paused;
background-color: lightgreen;
border-radius: 50%;
height: 0;
position: absolute;
width: 0;
}
轉到此處查看解決方案 #2 的 CodePen 工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.