如何在使用助手 class 添加和删除 class 时应用过渡

How to apply transition all on adding and removing a class with helper class

我正在尝试在添加和删除(切换)到 classes .fa-heart-o.fa-heart 时添加过渡,并使用名为 [=17= 的助手 class ] 像这样。但是正如您所看到的,.fa-heart-slow 没有在那里添加任何过渡。

我该如何解决这个问题?

$(".table").hover(function() {
  $(this).find(".fa").removeClass('fa-heart-o').addClass('fa-heart fa-heart-slow');

}, function() {
  $(this).find(".fa").removeClass('fa-heart-slow fa-heart').addClass('fa-heart-o');

});
@import url("https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css");
body {
  padding: 20px;
}

.fa-heart-slow {
  -webkit-transition: all 1s ease;
  -moz-transition: all 1s ease;
  -o-transition: all 1s ease;
  transition: all 1s ease;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table">
  <tr>
    <td><i class="fa fa-heart-o" aria-hidden="true"></i></td>
  </tr>

</table>

我不相信这会按照您的预期工作,因为切换 .fa classes 有效地切换了元素的 content 属性 和 content 属性 不在 W3 规范中列为支持过渡动画:https://www.w3.org/TR/css-transitions-1/#animatable-css

就是说,创建相同效果的一种简单方法是让两个图标相互重叠 - 每个 .fa class - 然后使用纯 CSS 进行动画处理悬停时所需的行为。这可以通过以下方式实现。

HTML:

<table class="table">
  <tr>
    <td><i class="fa fa-heart-o icon-default"></i><i class="fa fa-heart icon-hover"></i></td>
  </tr>
</table>

CSS:

.table .fa {
  transition: opacity 1s ease;
}
.icon-hover {
  opacity: 0;
  left: -16px;
  position: relative;
}
.table:hover .icon-default {
  opacity: 0;
}
.table:hover .icon-hover {
  opacity: 1;
}

首先,我根据您的示例为 1s ease 设置了过渡;我们仅为 opacity 设置它,因为这是唯一的 属性 变化。然后我将第二个 .fa 图标 (.icon-hover) 设置为 opacity:0 并将其放在主要图标 (.icon-default) 后面。

最后,应用了一个:hover规则,当悬停在.table元素上时切换两个图标的不透明度;结合之前定义的transition属性,两者出现交叉淡入淡出in/out.

CodePen 在这里:https://codepen.io/anon/pen/VELLgj