【问题标题】:Remove background color slowly and only once缓慢去除背景颜色,仅一次
【发布时间】:2016-01-05 02:08:10
【问题描述】:

它需要像新消息一样-通过悬停(参见下面的 css)它的背景会慢慢消失,但它只能是一次,这就是为什么我需要删除这个额外的类,例如“newmessage”给出了这个背景,但是如果我通过悬停删除这个类-我没有这种缓慢的效果......

.newmessage {
  background-color: rgba(213, 213, 213, 1);
  -webkit-transition: background-color 2s ease-out;
  -moz-transition: background-color 2s ease-out;
  transition: background-color 2s ease-out;
}
.newmessage:hover {
  background-color: rgba(213, 213, 213, 0);
}

【问题讨论】:

  • 你能把你应用这个类的 HTML 元素贴出来吗?
  • 这里是一个例子:jsfiddle.net/jaes2g9g

标签: javascript jquery css


【解决方案1】:

您可以添加一个类,以便在使用 JavaScript 悬停元素时应用样式规则。它只会添加一次,导致元素的样式发生过渡。 Updated version of your fiddle

演示

var newMessages = document.querySelectorAll('.newmessage');


for (var i = 0, l = newMessages.length; i < l; i++) {
    //added the .hovered class on mouseover
    newMessages[i].addEventListener('mouseover', function() {
        this.classList.add('hovered');
    });
}
div {
    background-color: gray;
    height: 50px;
    width: 200px;
    margin-bottom: 5px;
}
.newmessage {
  background-color: rgba(220, 55, 55, 1);
  -webkit-transition: background-color 2s ease-out;
  -moz-transition: background-color 2s ease-out;
  transition: background-color 2s ease-out;
}
/* instead of .newmessage:hover, use additional class */
.newmessage.hovered {
  background-color: rgba(220, 55, 55, 0);
}
<div></div>
<div></div>
<div class="newmessage"></div>

【讨论】:

    【解决方案2】:

    您正在寻找的是在过渡结束后执行回调以删除该类。

    Is there a callback on completion of a CSS3 animation?

    是的,有。回调是一个事件,所以你必须添加一个事件 听众抓住它。这是一个使用 jQuery 的例子:

    $("#sun").bind('oanimationend animationend webkitAnimationEnd', function() { 
       alert("fin") 
    });
    

    或者纯js:

    element.addEventListener("webkitAnimationEnd", callfunction,false);
    element.addEventListener("animationend", callfunction,false);
    element.addEventListener("oanimationend", callfunction,false);
    

    现场演示:http://jsfiddle.net/W3y7h/

    感谢@Duopixel

    在您的情况下,您可能必须使用transitionend 而不是animationend

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-05-27
      • 2020-02-15
      • 2017-09-04
      • 1970-01-01
      • 1970-01-01
      • 2011-07-27
      • 1970-01-01
      相关资源
      最近更新 更多