css动画将在点击时应用

时间:2016-06-15 14:20:02

标签: html css onclick

我正在尝试将CS​​S动画应用于我的HTML。我有以下代码:

HTML:

<button>Save</button>

CSS:

button{
width:100px;
height:40px;
background-color:yellow;
border-radius:10px;
   -webkit-animation-name: example;
  -webkit-animation-duration: 2s; 
  -webkit-animation-iteration-count: 3; 
animation-name: example;
animation-duration: 4s;
animation-iteration-count: infinite;
}

@-webkit-keyframes example {
0%   {background-color:yellow;}
50%  {background-color:green;}
}

我可以获得按钮更改颜色。但是我希望它能在点击时改变颜色。我如何实现这一目标?

2 个答案:

答案 0 :(得分:3)

如果您只是想在点击时更改按钮的颜色,则CSS过渡比动画更简单,您可以在没有任何JavaScript的情况下执行此操作:

&#13;
&#13;
#buttonState {
  display:none;
}

#buttonState + label {
    width: 100px;
    height: 40px;
    background-color: yellow;
    border-radius: 10px;
    transition: background-color 4s linear;
}

#buttonState:checked + label {
    transition: background-color 4s linear;
    background-color: green;
}
&#13;
<input type="checkbox" id="buttonState" class="btn-state" />
<label for="buttonState" class="btn">Save</label>
&#13;
&#13;
&#13;

您甚至可以将此元素看作具有some extra styles的按钮。

答案 1 :(得分:1)

对于纯CSS解决方案,请使用labelinput[type = "checkbox"]组合。 (代码笔:http://codepen.io/anon/pen/dXXXww)。

HTML:

<input type = "checkbox" id = "buttonState" class = "btn-state" />
<label for = "buttonState" class = "btn">
  Save
</label>

CSS(LESS):

.btn {
  box-sizing: border-box;
  display: inline-block;
  font: normal 20px/40px Sans-serif;
  text-align: center;
  width: 100px;
  height: 40px;
  background-color: yellow;
  border-radius: 10px;
  cursor: pointer;
}

.btn-state {
  display: none;
  &:checked + .btn {
    animation: example 4s infinite;
  }
}

@keyframes example {
  0%   {background-color: yellow;}
  50%  {background-color: green;}
}

对于JavaScript解决方案,请使用以下代码。 (代码笔:http://codepen.io/anon/pen/OXXXqP)。

HTML:

<button class = "btn">
  Save
</button>

CSS:

.btn {
  box-sizing: border-box;
  display: inline-block;
  font: normal 20px/40px Sans-serif;
  text-align: center;
  width: 100px;
  height: 40px;
  background-color: yellow;
  border-radius: 10px;
  cursor: pointer;
  outline: 0;
}

.btn.animate {
  animation: example 4s infinite;
}

@keyframes example {
  0%   {background-color: yellow;}
  50%  {background-color: green;}
}

JS:

var $ = document.querySelectorAll.bind(document);
$('.btn')[0].addEventListener('click', function(evt) {
  evt.target.classList.toggle('animate');
});