"Вспышка" цвета, используя чистые css-переходы

Я пытаюсь дать пользователям "вспышку" цвета, когда есть событие click. Я могу получить цвет, чтобы он выглядел приятным образом с использованием перехода, однако я хочу, чтобы цвет исчезал после .5s, не удаляя "активный" класс. Однако одно требование заключается в том, что я не могу использовать анимацию jQuery, и это должно быть сделано в CSS.

Ниже приведена css, которую я использую в настоящее время.

.active{
  background-color: yellow;
  -webkit-transition: background-color .5s linear;
  transition: background-color .5s linear;
}

Я попытался указать второе значение, но я не думаю, что это допустимая разметка, поскольку она не работает.

.active{
  background-color: yellow;
  -webkit-transition: background-color .5s linear, background-color:transparent .5s linear;
  transition: background-color .5s linear, background-color:transparent .5s linear;
}

http://jsbin.com/itivum/1/edit

Ответы

Ответ 1

Я думаю, это то, что вы ищете. Образец не является точным.

$("#go").click(function() {
    $("#box").removeClass("demo");
    setTimeout(function() {
        $("#box").addClass("demo");
    }, 1);
});
.container {position: relative;}

#box {
    height: 100px; 
    width: 100px; 
    background-color: #777;
    position: absolute;
    left: 5px;
    top: 5px;
    opacity: 0;
}

@-webkit-keyframes demo {
    0% {
        background-color: Yellow;
        opacity:1;
    }
    22% {
        background-color: Yellow;
    }
    77% {
        background-color: Red;
    }
    100% {
        background-color: #777;
    }
}
    
.demo {
    -webkit-animation-name: demo;
    -webkit-animation-duration: 900ms;
    -webkit-animation-iteration-count: 1;
    -webkit-animation-timing-function: ease-in-out;
}    
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<button id="go">Go</button>
<div class="container">
    <div id="box"></div>
</div>

Ответ 2

Я придумал следующее, основанное на моих собственных потребностях. Я хотел, чтобы вспышка цвета подтвердила действие пользователя. Текст мигает один раз, когда вы нажимаете на него. Он использует jquery для установки класса, но не для анимации.

Html:

<span style="background:lightgray" id="id">Click to flash</span>

Js:

$('#id').click(function() {
    $('#id').addClass('flash');
    setTimeout(function() {
          $('#id').removeClass('flash');
    }, 500);
});

Css:

.flash {
    -webkit-animation-name: flash-animation;
    -webkit-animation-duration: 0.3s;

    animation-name: flash-animation;
    animation-duration: 0.3s;
}

@-webkit-keyframes flash-animation {  
    from { background: yellow; }
    to   { background: default; }
}

@keyframes flash-animation {  
    from { background: yellow; }
    to   { background: default; }
}

См. http://jsfiddle.net/umz8t/3597/

Ответ 3

Вы можете попытаться немного поиграть с псевдоэлементом, связав два перехода

первый переход только меняет цвет (с быстрым эффектом), а второй просто меняет непрозрачность псевдоэлемента (так скоро исчезает) после задержки 0.1s. Не стесняйтесь изменять эти значения, как вы предпочитаете

#imADiv{
  margin-top:50px;
  height:150px;
  width:150px;
  position:absolute;
}

#imADiv:before {
  position: absolute;
  z-index: -1;
  top: 0; left: 0; width: 100%; height:100%;
  content: "";
  -webkit-transition: background .1s linear 0s, opacity .01s linear .1s;
  transition: background .1s linear 0s, opacity .01s linear .1s;

}

#imADiv.active:before {
  background-color: yellow;
  opacity: 0;
}

Пример jsbin: http://jsbin.com/isihos/3/edit

Ответ 4

Впечатленный ответом Рохита, вот моя собственная демонстрация JSFiddle (с дополнительными функциями)

Основная часть - это CSS (или, как я предпочитаю, SCSS):

@-webkit-keyframes quickFlash {
  0% {
    background-color: yellow;
    opacity: 1;
  }
  100% {
    background-color: inherit;
  }
}

.quickFlash {
  //https://stackoverflow.com/info/16791851/a-flash-of-color-using-pure-css-transitions
  -webkit-animation-name: quickFlash;
  -webkit-animation-duration: 1900ms;
  -webkit-animation-iteration-count: 1;
  -webkit-animation-timing-function: ease;
  -moz-animation-name: quickFlash;
  -moz-animation-duration: 1900ms;
  -moz-animation-iteration-count: 1;
  -moz-animation-timing-function: ease;
}

И еще мне было полезно иметь возможность удалить класс в конце анимации (чтобы позже я мог добавить его снова, если захочу снова увидеть анимацию):

function flashYellow(element) {
  element
    .addClass("quickFlash")
    .on(
      "webkitAnimationEnd oanimationend msAnimationEnd animationend",
      function() {
        console.log("animationend");
        $(this)
          .delay(500)// Wait for milliseconds.
          .queue(function() {            
            console.log("end of delay");
            $(this)
              .removeClass("quickFlash")
              .dequeue();
          });
      }
    );
}