悬停CSS转换时防止闪烁

时间:2019-02-03 03:48:40

标签: css css-transforms

如果鼠标不在图像中心附近,则将鼠标悬停在垂直旋转的锚点上时,动画转换会使用以下代码闪烁:

@keyframes spin {0% {transform: rotateX(0deg);} 100% {transform: rotateX(360deg);}}
a:focus, a:hover {animation: spin 0.9s 1 linear;}

如何在不更改HTML的情况下防止闪烁?

https://jsfiddle.net/jabcreations/ahcx0wfv/

2 个答案:

答案 0 :(得分:3)

为避免将:hovera中移出并闪烁,您可以将:hovera移到其父节点:

@keyframes spin {
  100% {
    transform: rotateX(360deg);
  }
}

ul {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

li:hover {
  cursor: pointer;
}

a:focus,
li:hover a {
  animation: spin 0.9s 1 linear;
}

ul a {
  color: #000;
  display: inline-block;
  height: 50px;
}

ul a:focus,
ul li:hover a {
  background-image: radial-gradient(ellipse at center, #777 0%, #222 100%);
  color: #fff;
}
<ul>
  <li><a href="admin/">Admin</a></li>
  <li><a href="appointments/">Appointments</a></li>
  <li><a href="blog/">Blog</a></li>
  <li><a href="calendar/">Calendar</a></li>
  <li><a href="contact/">Contact</a></li>
  <li><a href="events/">Events</a></li>
  <li><a href="forms/">Forms</a></li>
  <li><a href="forums/">Forums</a></li>
  <li><a href="guestbook/">Guestbook</a></li>
  <li><a href="mail/">Mail</a></li>
  <li><a href="members/">Members</a></li>
  <li><a href="newsletter/">Newsletter</a></li>
  <li><a href="notifications/">Notifications</a></li>
  <li><a href="search/">Search</a></li>
</ul>

答案 1 :(得分:1)

不更改html的想法是将动画移动到伪元素,由于主要元素不会旋转,您将避免悬停:

您还可以使用过渡而不是动画来简化逻辑:

p a {
  color: #000;
  display: inline-block;
  height: 50px;
  z-index:0;
  position:relative;
  color:transparent;
}
p a:before {
  content:attr(data-text);
  position:absolute;
  z-index:-1;
  top:0;
  left:0;
  right:0;
  bottom:0;
  color:#000;
  transition:transform 0.9s linear;
}
p a:focus::before,
p a:hover::before {
  transform: rotateX(360deg);
  background: radial-gradient(ellipse at center, #777 0%, #222 100%);
  color: #fff;
}
<p>some content here <a href="admin/" data-text="Admin">Admin</a> and more here</p>