首页 > 解决方案 > 设置相同元素的按钮单击动画效果

问题描述

我有这样的 div 。H1 标签根据按钮点击动态显示数据。

    <div id="quoteId" >
          <h1>{{ data }}</h1>
        </div>
<button>Show Next</button>

使用 css3 动画效果作为

#quoteId {
    opacity: 1;
    animation-name: example;
    animation-duration: 1s;
}
@keyframes example {
    0%   {opacity: 0;}
    50%  {opacity: 1;}
    100% {opacity: 1;}
}

它在第一次工作。但问题是每次单击按钮时如何实现相同的css效果。如果有任何不清楚的地方,请告诉我。提前致谢。

标签: javascriptcss

解决方案


A) 使用 jQuery:

$("#quoteId").toggleClass('anime reve');

$(document).ready(function(){
  $('button').click(function(){
    $("#quoteId").toggleClass('anime reve');
  })
})
.anime {
  animation-name: example;
  animation-duration: 5s;
}

.reve {
  animation-name: reve;
  animation-duration: 5s;
}

@keyframes example {
  0%   {opacity: 0;}
  50%  {opacity: 1;}
  100% {opacity: 1;}
}

@keyframes reve {
  0%   {opacity: 0;}
  50%  {opacity: 1;}
  100% {opacity: 1;}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div id="quoteId" class="reve" >
  <h1>{{ data }}</h1>
</div>
<button>Show Next</button>

B)使用纯CSS:

注意: :active 选择器仅在按下按钮时应用。

使用选择器后,您必须稍微更改 html 代码active

button:active + #quoteId {
  animation-name: example;
  animation-duration: 20s;
}

@keyframes example {
  0%   {opacity: 0;}
  50%  {opacity: 1;}
  100% {opacity: 1;}
}


button:active + #quoteId {
  animation-name: example;
  animation-duration: 1s;
}

.container {
  position: relative;
  padding-bottom: 20px;
}

button {
  position: absolute;
  bottom: 0;
}
<div class="container">
  <button>Show Next</button>
  <div id="quoteId">
    <h1>{{ data }}</h1>
  </div>
</div>


推荐阅读