突出显示元素然后过渡回原始颜色

Highlight element then transition back to original color

我有不同 background-color 的元素。单击 link 时,我想用不同的颜色(黄色)突出显示元素,然后淡化回元素的原始颜色。我知道元素的 colorcurrentColor,但是 background-color.

没有类似的东西

如何从高亮颜色平滑过渡回元素的原始颜色background-color现在它从高亮颜色淡化为透明,然后突然跳回到动画结束时的原始颜色。

:target td {
  animation: highlight 1s;
}

@keyframes highlight {
  from {
    background-color: yellow;
  }
  to {
  /* How do I set this back to the element's original background-color? */
    background-color: transparent;
  }
}
<ul>
  <li>
    <a href="#link1">Link #1</a>
  </li>
  <li>
    <a href="#link2">Link #2</a>
  </li>
    <li>
    <a href="#link3">Link #3</a>
  </li>
</ul>

<table>
  <tr id="link1">
    <td>This is Link #1</td><td>// Fine.</td>
  </tr>
  <tr id="link2">
    <td bgcolor="orange">This is Link #2</td><td>// Ugly.</td>
  </tr>
    <tr id="link3">
    <td bgcolor="red">This is Link #3</td><td>// Ugly.</td>
  </tr>
</table>

只是不要为动画添加 to。这是可行的,因为如果未定义结束(或开始)状态,浏览器将使用元素的现有样式(回复:Valid Keyframe Lists on MDN

div {
  margin: 200px 0;
}

:target td {
  animation: highlight 1s;
}

@keyframes highlight {
  from {
    background-color: yellow;
  }
}
<ul>
  <li>
    <a href="#link1">Link #1</a>
  </li>
  <li>
    <a href="#link2">Link #2</a>
  </li>
    <li>
    <a href="#link3">Link #3</a>
  </li>
</ul>

<table>
  <tr id="link1">
    <td>This is Link #1</td><td>// Fine.</td>
  </tr>
  <tr id="link2">
    <td bgcolor="orange">This is Link #2</td><td>// Ugly.</td>
  </tr>
    <tr id="link3">
    <td bgcolor="red">This is Link #3</td><td>// Ugly.</td>
  </tr>
</table>

如果您只是从关键帧中删除 to,它将采用指定的背景颜色。

要理解它,请阅读 mdn 文档的这一部分 https://developer.mozilla.org/en-US/docs/Web/CSS/@keyframes#Valid_keyframe_lists

div {
  margin: 200px 0;
}

:target td {
  animation: highlight 2s;
}

@keyframes highlight {
  from {
    background-color: yellow;
  }
}
<ul>
  <li>
    <a href="#link1">Link #1</a>
  </li>
  <li>
    <a href="#link2">Link #2</a>
  </li>
    <li>
    <a href="#link3">Link #3</a>
  </li>
</ul>

<table>
  <tr id="link1">
    <td>This is Link #1</td><td>// Fine.</td>
  </tr>
  <tr id="link2">
    <td bgcolor="orange">This is Link #2</td><td>// Ugly.</td>
  </tr>
    <tr id="link3">
    <td bgcolor="red">This is Link #3</td><td>// Ugly.</td>
  </tr>
</table>

另一种选择是在 50% 的动画上使用 background-color: initial - 请参见下面的演示:

div {
  margin: 200px 0;
}

:target td {
  animation: highlight 2s;
}

@keyframes highlight {
  0% {
    background-color: yellow;
  }
  50% {
    background-color: initial;
  }
}
<ul>
  <li>
    <a href="#link1">Link #1</a>
  </li>
  <li>
    <a href="#link2">Link #2</a>
  </li>
    <li>
    <a href="#link3">Link #3</a>
  </li>
</ul>

<table>
  <tr id="link1">
    <td>This is Link #1</td><td>// Fine.</td>
  </tr>
  <tr id="link2">
    <td bgcolor="orange">This is Link #2</td><td>// Ugly.</td>
  </tr>
    <tr id="link3">
    <td bgcolor="red">This is Link #3</td><td>// Ugly.</td>
  </tr>
</table>