子元素的平滑悬停过渡

Smooth unhover transition for child element

我有一个内联块图像 div 和父 link 元素中的跨度。
我将图像用作自定义列表项目符号。

我想在悬停整个 link 元素时为列表项目符号设置动画,这是我使用以下选择器实现的:

a:hover > div.bullet {
    animation: ... ;
    transition: all 0.5s ease;
}

但是,无论我做什么,我都无法添加相同的平滑过渡以将 div 返回到其原始位置。

这是一个工作示例:

a {
  display: flex;
  align-items: center;
  margin: 1rem 0;
  width: 100%;
  text-decoration: none;
  color: black;
  transition: all 0.5s ease;
}

a .bullet {
  margin-right: 1rem;
  height: 1.2rem;
  width: 1.2rem;
  background-image: url('https://www.pngkey.com/png/full/317-3170031_triangle-clipart-small-orange-pennant.png');
  background-position: 50% 50%;
  background-repeat: no-repeat;
  background-size: 20px 20px;
}

a:hover > .bullet {
  animation: bob 0.5s ease forwards;
}

@keyframes bob {
  from {
    transform: translateX(0);
  }
  to {
    transform: translateX(0.5rem);
  }
}
<a id="action1" href="#">
  <div class="bullet"></div>
  <span>item 1</span>
</a>

<a id="action2" href="#">
  <div class="bullet"></div>
  <span>item 2</span>
</a>

有什么想法吗?

我们可以消除关键帧动画,只在 .bullet 元素上设置未悬停的 transform,为 :hover class 设置悬停的 transform .这是否满足您的要求?

a {
  display: flex;
  align-items: center;
  margin: 1rem 0;
  width: 100%;
  text-decoration: none;
  color: black;
  transition: all 0.5s ease;
}

a .bullet {
  margin-right: 1rem;
  height: 1.2rem;
  width: 1.2rem;
  background-image: url('https://www.pngkey.com/png/full/317-3170031_triangle-clipart-small-orange-pennant.png');
  background-position: 50% 50%;
  background-repeat: no-repeat;
  background-size: 20px 20px;
  transition: all 0.5s ease;
  transform: translateX(0)
}

a:hover > .bullet {
  transform: translateX(0.5rem);
}
<a id="action1" href="#">
  <div class="bullet"></div>
  <span>item 1</span>
</a>

<a id="action2" href="#">
  <div class="bullet"></div>
  <span>item 2</span>
</a>

我会说这就是伪元素的用途。只需添加一个 ::before 元素,然后在悬停时单独为该元素设置动画。

请注意,永远不要为 all 元素设置动画,因为它会遍历所有可设置动画的属性,如果页面忙于其他事情(如 javascript 执行或其他类型的动画。

a {
  display: flex;
  margin: 1rem 0;
  text-decoration: none;
  color: black;
}

a.bullet::before {
  content: '';
  margin-right: 1rem;
  height: 1.2rem;
  width: 1.2rem;

  background-image: url('https://www.pngkey.com/png/full/317-3170031_triangle-clipart-small-orange-pennant.png');
  background-position: 50% 50%;
  background-repeat: no-repeat;
  background-size: 20px 20px;
  
  transition: transform 0.5s ease;
}

a.bullet:hover::before  {
  transform: translateX(0.5rem);
}
<a id="action1" class="bullet" href="#">item 1</a>
<a id="action2" class="bullet" href="#">item 2</a>