我希望 div 框的顏色和大小在單擊按鈕時具有影片效果并回傳其原始值。這是我的代碼示例:
document.getElementById("andAction").addEventListener("click", function() {
document.getElementById("box").classList.toggle("animi");
})
.thing {
transform: translate(150px, 100px);
}
.box {
background-color: #999;
padding: 2px;
color: black;
width:20px;
margin: 0 auto;
text-align: center;
color: #fff;
}
@keyframes blob {
0% {
background-color: #999;
}
50% {
background-color: #F9086D;
transform: scale(2);
background-color: red;
border-radius: 20px;
}
100% {
background-color: #999;
}
}
.animi {
animation-name: blob;
animation-duration:3s;
animation-iteration-count:1;
}
<button id="andAction" class="button">button</button>
<div id="box" class="box">1</div>
問題
我的問題是我用切換來做。這意味著我必須在第二次點擊兩次。另一個品種是classList.add然后再次洗掉。這導致沒有結果,因為影片不是為用戶啟動的。我唯一能做的就是處理超時。
題
我感覺還有別的方法嗎?
uj5u.com熱心網友回復:
您可以onanimationend在影片結束時偵聽事件以洗掉類,而無需依賴難以維護的計時器:
const boxElement = document.getElementById("box")
boxElement.addEventListener('animationend', (e) => {
// if the target it the box (it's triggered by animations on children too)
// and the animation name is `blob` (it's triggered by any animation)
// remove the class
if (e.target === boxElement && e.animationName === "blob") {
boxElement.classList.remove('animi');
}
})
document.getElementById("andAction").addEventListener("click", function() {
boxElement.classList.add("animi");
})
uj5u.com熱心網友回復:
只需添加一些 js 即可在影片完成后自動洗掉該類,并將您的初始行為更改為不切換,而只需添加該類。您可以通過使用https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/animationend_event來實作。
const box=document.getElementById("box");
document.getElementById("andAction").addEventListener("click", function() {
box.classList.add("animi");
});
box.addEventListener('animationend', () => {
box.classList.remove("animi");
});
.thing {
transform: translate(150px, 100px);
}
.box {
background-color: #999;
padding: 2px;
color: black;
width: 20px;
margin: 0 auto;
text-align: center;
color: #fff;
}
@keyframes blob {
0% {
background-color: #999;
}
50% {
background-color: #F9086D;
transform: scale(2);
background-color: red;
border-radius: 20px;
}
100% {
background-color: #999;
}
}
.animi {
animation-name: blob;
animation-duration: 3s;
animation-iteration-count: 1;
}
<button id="andAction" class="button">button</button>
<div id="box" class="box">1</div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/324361.html
標籤:javascript css 动画片 css动画
