【问题标题】:In CSS, briefly flash the bg of an element [closed]在 CSS 中,短暂闪烁元素的 bg [关闭]
【发布时间】:2020-06-19 10:00:45
【问题描述】:

我正在制作一个简单的网页,在 vanilla javascript 中具有简单的功能。我不时更改<span>innerHTML。有没有一种简单的方法可以“闪现”这个跨度?即背景应该短暂变成(例如)红色,然后淡出回到默认的白色背景。只是为了提醒用户有东西更新了。

我想用现代、简单的 CSS 来做这件事,因为我想了解更多。我确信我可以手动为所有这些设置动画,但我想知道是否有 ✨modern✨ 方法可以做到这一点。假设我使用的是现代网络浏览器。这是一个内部工具,我不需要支持每个网络浏览器。但我宁愿使用标准的投诉方式。

【问题讨论】:

  • 您可以将 CSS 类添加到跨度并触发 setTimeout() 以从跨度中删除该类。如果你想花哨,你可以添加过渡。你也可以使用这个现成的实用程序animate.style
  • 当元素的内容发生变化时颜色应该改变这一事实意味着你不能简单地使用 CSS,还需要一些 JavaScript。

标签: javascript html css animation


【解决方案1】:

由于<span> 元素的闪烁是由其内容的更改触发的,因此仅靠 CSS 不足以实现该功能。您还需要使用一些 JavaScript,以便能够在内容更改时触发颜色更改。元素上的CSS Transition 将处理其余部分(即淡入和淡出动画)。

这是一个简单的代码 sn-p(支持您的“现代网络浏览器”),说明如何使用 setTimeout 延迟第二个动画(否则,更改将是瞬间完成)。

function updateContent(element, content) {
    // update content
    element.innerHTML = content;
    // change the background color (will trigger the CSS configured transition)
    element.style.backgroundColor = 'red';
    // change the background color back (with a delay equal to transition length)
    setTimeout(() => { element.style.backgroundColor = 'white'; }, 500);
}

// delayed initial update (just to better visualize what's happening)
setTimeout(() => {
    updateContent(document.getElementById('flashy'), 'new content');
}, 1000);
#flashy {
    background-color: white;
    transition: background-color 500ms linear;
}
<span id="flashy">initial content</span>

【讨论】:

    【解决方案2】:

    如果您在这里分享了您的代码,那么我本可以为您提供更好的帮助,但无论如何 你可以在 CSS transition 属性的帮助下做这样的事情。 做这些事情真的很方便。

    For more Info on transition property check this.

    【讨论】:

      猜你喜欢
      • 2019-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-13
      • 2015-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多