由于这个代码是现在,我必须按两次才能显示文本并褪色.

我怎么能只按一次按钮有"添加!"文本出现和褪色?我希望这种情况发生在每次我点击按钮(即使用户点击,而文本是褪色,它应该开始从完全可见到褪色).

我试着用CSS来做重点.我也试过重新排列javascript代码,以及在javascript中插入while循环,但我一定做错了什么.

谢谢

  function cartAdded() {
    var text = document.getElementById("added-notification");
    if (text.style.display === "none") {
      text.style.display = "block";
    } else {
      text.style.display = "none";
    }
  }
  .added-fade-out {
    opacity: 0;
    display: none;
    animation: fadeOut 1s ease-out;

  }

  @keyframes fadeOut {
    0% {
      opacity: 1;
      display: none;
    }

    50% {
      opacity: 0.5;
      display: block;
    }

    100% {
      opacity: 0;
      display: none;
    }
  }
  <button type='button' onclick="cartAdded()">Click me</button>
  <p id='added-notification' class="added-fade-out">Added!</p>

推荐答案

你需要使用animationend事件删除你的fade Out

const
  notificationButton = document.querySelector('#notification-btn')
, pNotificationText  = document.querySelector('#notification-text')
  ;

notificationButton.addEventListener('click', () =>
  {
  notificationButton.disabled = true;
  pNotificationText.classList.replace('noDisplay','show-fade-out')
  })
pNotificationText.addEventListener('animationend', () =>
  {
  notificationButton.disabled = false;
  pNotificationText.classList.replace('show-fade-out','noDisplay') 
  })
.noDisplay {
  display: none;
  }
.show-fade-out {
  animation: fadeOut 1s ease-out forwards;
  }
@keyframes fadeOut {
  100% { opacity: 0; }
  }
<button id="notification-btn">Click me</button>
<p id='notification-text' class="noDisplay" > Added! </p>

Javascript相关问答推荐

橡皮擦完全让画布变成白色

在具有焦点和上下文的d3多线图表中,如何将上下文的刷新限制在特定日期?

为什么JavaScript双边字符串文字插值不是二次的?

窗口.getComputedStyle()在MutationObserver中不起作用

深嵌套的ng-container元素仍然可以在Angular 布局组件中正确渲染内容吗?

使用javascript将Plotly Expandable Sparkline转换为HighCharter Plot在bslib卡中

如何将Map字符串,布尔值转换为{key:string;value:bo布尔值;}[]?<>

如何在JavaScript文件中使用Json文件

我的角模板订阅后不刷新'

Reaction Native中的范围滑块

在Java中寻找三次Bezier曲线上的点及其Angular

如何在Angular拖放组件中同步数组?

Use Location位置成员在HashRouter内为空

在VS代码上一次设置多个变量格式

当从其他文件创建类实例时,为什么工作线程不工作?

JAVASCRIPT SWITCH CASE语句:当表达式为';ALL';

使用可配置项目创建网格

在没有任何悬停或其他触发的情况下连续交换图像

我怎样才能点击一个元素,并获得一个与 puppeteer 师导航页面的URL?

如何设置时间选取器的起始值,仅当它获得焦点时?