javascript - 在使用 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,它就会开始播放动画,但我希望它在单击按钮后播放。
我还有一些其他内容html
,css
但为了简短起见,我删除了不相关的内容。请让我知道我应该在哪里添加或删除JQuery
或删除什么CSS
以获得所需的输出。谢谢!
PS,因为这是我的第一个问题,可能无法正确描述。带来不便敬请谅解。
解决方案
您需要在单击后激活动画,但您不能::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 ";
}
推荐阅读
- php - 如何解决摘录内搜索结果中的重复项
- jsp - 当用户单击添加到购物车时,项目应存储在表格中
- reactjs - 使用 React 设计(真实房屋的)窗框
- javascript - Android 应用程序强制关闭,SQLite 数据库的东西
- javascript - onEachfeatures 不显示内容但 [object Object]
- raku - 带有自定义词法分析器的 Raku 语法
- javascript - 如何编辑图像 JavaScript 的加载优先级
- reactjs - 如何将条件道具传递给打字稿中未知类型的反应组件?
- c++ - PCL、SACS分割检测球
- asp.net-core - Asp.Net core 3.1 web 应用程序在运行时意外终止,没有任何异常