首页 > 解决方案 > 在使用 JQuery 或 JavaScript 单击按钮时将 CSS 动画添加到 h1

问题描述

所以...我有一个 h1 和一个按钮。我想CSS在单击按钮时将我创建的动画添加到 h1 中JQuery

当您单击按钮时,动画应添加更多内容到h1. 我希望它在我单击按钮时启动,但它会在我加载HTML.

由于我对这项技能不熟悉,因此我无法理解其他复杂的答案。请帮帮我。

这是HTML

<div class="container-fluid center" id="mainPage">
    <div id="heading" class="row">
        <h1 id="wishH1">NAME!</h1>
    </div>
</div>
<div class="container-fluid center" id="gift">
    <button type="button" id="giftButton">
        <img id="giftImg" src="gift.png">
    </button>
</div>

这是CSS:

@keyframes wish {
  25% {
    content: : "hi ";
  }
  50% {
    content: : "hello ";
  }
  75% {
    content: "hola ";
  }
}

#wishH1::before {
  content: "hey there ";
  animation: wish 20s linear infinite;
}

这是JQuery

不同的评论显示了我在删除动画部分后尝试做的不同事情,CSS但他们甚至没有开始动画......

$('#giftButton').click(function() {
  $("#gift").fadeOut(1500);
  /*$("#wishH1").css("animation",wish);
    $("#wishH1").css("animation-duration",6s);
    $("#wishH1").css("animation-timing-function",linear);
    $("#wishH1").css("animation-iteration-count",infinite);*/
  /*$("#wishH1").animate({animation: "wish 6s linear infinite"});*/
  /*("#wishH1").css("animation-play-state","running");*/
  setTimeout(function() {
    $("#gift").fadeIn(1500);
  }, 20000);
});

h1变化如下:

hey there NAME!

hi NAME!

hello NAME!

hola NAME!

现在,只要我启动 html,它就会开始播放动画,但我希望它在单击按钮后播放。

我还有一些其他内容htmlcss但为了简短起见,我删除了不相关的内容。请让我知道我应该在哪里添加或删除JQuery或删除什么CSS以获得所需的输出。谢谢!

PS,因为这是我的第一个问题,可能无法正确描述。带来不便敬请谅解。

标签: javascripthtmljquerycss

解决方案


您需要在单击后激活动画,但您不能::before在 jQuery 中选择伪元素(部分),因为它们不是 DOM 的一部分。但是你可以给父元素添加一个特定的类 ( animation-start) 并在 CSS 中控制它的伪元素。

$('#giftButton').click(function() {
  $("#gift").fadeOut(1500);
  $('#wishH1').addClass('animation-start');
  setTimeout(function() {
    $("#gift").fadeIn(1500);
  }, 20000);
});
@keyframes wish {
  25% {
    content: "hi ";
  }
  50% {
    content: "hello ";
  }
  75% {
    content: "hola ";
  }
}

#wishH1::before {
  content: "hey there ";
}

#wishH1.animation-start::before {
  animation: wish 5s linear infinite;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container-fluid center" id="mainPage">
  <div id="heading" class="row">
    <h1 id="wishH1">NAME!</h1>
  </div>
</div>
<div class="container-fluid center" id="gift">
  <button type="button" id="giftButton">
        <img id="giftImg" src="gift.png">
    </button>
</div>

您的 CSS 中还有额外的分号,可能会给您带来一些麻烦。

@keyframes wish{
25%{
    content:: /* here */ "hi "; 
}
50%{
    content:: /* here */ "hello "; 
}
75% {
    content: "hola ";
}

推荐阅读