如何强制整个动画:悬停:用css3之后

时间:2018-02-09 08:51:56

标签: javascript html css css3

这是悬停中的简单动画

https://codepen.io/riccardomarconato/pen/EQZJEb

body{
  background-color: black;
}

h1 {
  text-align: center;
  margin-top: 50px;
}

a {
  text-decoration: none;
  color: #fff;
}

.underlineFromLeft {
  display: inline;
  position: relative;
  overflow: hidden;
}

.underlineFromLeft:after {
  content: "";
  position: absolute;
  z-index: 100;
  right: 0;
  width: 0;
  bottom: -2px;
  background: #fff;
  height: 40px;
  transition-property: width;
  transition-duration: 0.3s;
  transition-timing-function: ease-out;
}

.underlineFromLeft:hover:after {
  left: 0;
  right: auto;
  width: 100%;
}
<h1><a class="underlineFromLeft" href="">Hover me</a></h1>

效果很好,但只有在动画结束之前不离开鼠标悬停。我试着弄清楚以下js但是没有用。

$(".underlineFromLeft").bind("webkitAnimationEnd mozAnimationEnd animationEnd", function(){
  $(this).removeClass("underlineFromLeftAnimate:after")
})

$(".underlineFromLeft").hover(function(){
  $(this).addClass("underlineFromLeftAnimate:after");
})

$(".underlineFromLeft").bind("webkitAnimationEnd mozAnimationEnd animationEnd", function() {
  $(this).removeClass("underlineFromLeftAnimate:after")
})

$(".underlineFromLeft").hover(function() {
  $(this).addClass("underlineFromLeftAnimate:after");
})
body{
  background-color: black;
}

h1 {
  text-align: center;
  margin-top: 50px;
}

a {
  text-decoration: none;
  color: #fff;
}

.underlineFromLeft {
  display: inline;
  position: relative;
  overflow: hidden;
}

.underlineFromLeft:after {
  content: "";
  position: absolute;
  z-index: 100;
  right: 0;
  width: 0;
  bottom: -2px;
  background: #fff;
  height: 40px;
  transition-property: width;
  transition-duration: 0.3s;
  transition-timing-function: ease-out;
}

.underlineFromLeft:hover:after {
  left: 0;
  right: auto;
  width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1><a class="underlineFromLeft" href="">Hover me</a></h1>

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

  

Codepen fork

更改CSS,删除带有类名的:hover伪类,如此

.underlineFromLeft.hovered:after {
   left: 0;
   right: auto;
   width: 100%;
}

然后更改您的JS:请注意,您正在寻找的事件是transitionend(而不是animationend,因为您正在触发CSS转换)

$(".underlineFromLeft")
   .on("transitionend", function(){
       this.classList.remove("hovered")
   })
   .on('mouseenter', function() {
       this.classList.add("hovered");
   })