我有一个按钮,它使矩形表面出现并在单击时重新出现.一次单击按钮将显示“ home_card”,再次单击将使其消失.出现的效果功能应该在移除表面时为动画设置问题.
我试图在home_card元素上使用事件监听器,然后仅在“ transitionend”上删除该元素.这是我应该阅读的方式,但是我仍然做错了什么.谁能发现错误?
我的JavaScript文件如下:
function card_AppearsHome() {
if (transition_counter == 1){
HOW CAN I INSERT A "DISAPPEARING TRANSITION" before removing the element? I know you can use an eventlistener for the "ontransitionend" event,but not how you can do it..
document.getElementById("white_background_top").removeChild(home_card);
transition_counter = 0;
}
else {
//card/ div is created and appears,need to select a tranform: transition method
home_card = document.createElement('div');
home_card.id = "home_card";
home_card.className = "homecard_appear"
document.getElementById("white_background_top").appendChild(home_card);
transition_counter = 1;
}
}
/* card appearing effect */
.homecard_appear{
animation-name: card_app_anim;
animation-duration: 4s;
}
/* standard transition */
@keyframes card_app_anim {
from {left: 54vw;}
to {left: 94vw;}
}
/* Safari 4.0 - 8.0 transition */
@-webkit-keyframes card_app_anim {
from {left: 54vw;}
to {left: 94vw;}
}
这是CSS中消失效果的代码,我无法理解如何正确执行Javascript文件中的内容.
/* card disappearing effect */
.homecard_dissappear{
animation-name: card_dis_anim;
animation-duration: 4s;
}
/* standard transition */
@keyframes card_dis_anim {
from {left: 94vw;}
to {left: 54vw;}
}
/* Safari 4.0 - 8.0 transition */
@-webkit-keyframes card_dis_anim {
from {left: 94vw;}
to {left: 54vw;}
}
最佳答案
应该这样做(将代码部分替换为您在其中询问问题的地方):
if (transition_counter === 1) {
const home_card = document.querySelector('#homeCard');
home_card.addEventListener('onanimationend',function() {
home_card.remove();
transition_counter = 0;
});
home_card.classList.add('homecard_dissappear');
}
它为onanimationend添加了一个事件侦听器(删除了该元素并重置了transition_counter),并添加了homecard_dissappear类(启动了该过渡).过渡结束时,事件触发,该函数运行.
如果您在执行时遇到任何麻烦,请考虑使用一个可重现的示例来更新问题,我将更新我的答案.
最初,我的示例错误地使用了ontransitionend(在问题中建议)并围绕提供添加事件侦听器的语法展开,因为这似乎是OP的主要问题.
但是,正如folo和Hitesh Lala在评论中指出的那样,上述动画不会触发ontransitionend,因为它不包含任何过渡.因此,要绑定的适当事件是onanimationend.