每次用户单击时如何重播此CSS动画? [英] How to replay this CSS animation each time a user clicks?

查看:39
本文介绍了每次用户单击时如何重播此CSS动画?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个显示文本已复制!"的按钮.每次用户单击复制"按钮时.我完成此操作的方法是将动画分配给相关标签,还使用setTimeout来重置"动画.这样,当用户第二次或第三次单击按钮时,动画将再次播放.

I've created a button that displays the text "Copied!" each time the user clicks on the "Copy" button. The way I've accomplished this is by assigning the animation to the relevant tag and by also using setTimeout to "reset" the animation. This way, when a user clicks the button a second or third time, the animation plays again.

但是,我确定这不是理想的解决方案,因为如果用户在setTimeout完成之前单击,则按钮断开"直到经过2500ms.之后,它又可以工作了.

However, I'm certain this is not an ideal solution because if a user clicks before setTimeout finishes, the button 'breaks' until 2500ms have passed. After that, it works again.

如何重构CSS/JS,以便复制!"每次单击按钮时都会显示消息?(不受超时限制/延迟)

How can I refactor the CSS/JS so that the "Copied!" message displays each time the button is clicked? (Without being limited/delayed by a timeout)

  const copyURL = () => {
    const copyDiv = document.querySelector(".copyAlert")
    copyDiv.textContent = "Copied!";
    copyDiv.style.animationName = "disappear";
    copyDiv.style.animationDuration = "2.5s"; 
    setTimeout(function(){ 
    copyDiv.style.animationName = "none"; 
    }, 2400);

  };

.copyAlert {
  opacity: 0;
}

@keyframes disappear {
  30% {
    opacity: 0;
  }

  60% {
    opacity: 1;
  }

  100% {
    opacity: 0;
  }
}

<button onclick="copyURL()">Copy</button>

<span class="copyAlert"></span>

推荐答案

1)使用 animationend 事件
2)将 animate 类用于动画
3)不要使用JS插入已复制!"文本,只需将其写在您的html中

1) Use animationend event
2) Use animate class for animation
3) Don't use JS to insert "Copied!" text, just write it in your html

const copyURL = () => {
  const copyDiv = document.querySelector('.copyAlert:not(.animate)')
  if(copyDiv) {
    copyDiv.classList.add('animate');
    copyDiv.addEventListener('animationend', () => copyDiv.classList.remove('animate') );
  }
};

.animate { animation: disappear 2.5s linear; }

.copyAlert { opacity: 0; }

@keyframes disappear {
  30%  { opacity: 0; }
  60%  { opacity: 1; }
  100% { opacity: 0; }
}

<button onclick="copyURL()">Copy</button>
<span class="copyAlert">Copied!</span>

这篇关于每次用户单击时如何重播此CSS动画?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆