2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

開発部・CSSの裏技 - 定期的に変わる文字列

Posted at

関係ありません(迫真)

今回は定期的に文字列が変わるページを作る方法についてです。
皆さん疑似要素にCSSで文字列を表示できるのは知ってますよね?

span::after{
    content: "やりますねぇ";
}

これ×animationを使うとCSSで(JavaScript無しで)文字列を変更できます。

@keyframes text{
    0%{ content: ""; }
    25%{ content: "こ"; }
    50%{ content: "こ↑"; }
    75%{ content: "こ↑こ"; }
    100%{ content: "こ↑こ↓"; }
}
span::after{
    animation: text 1s linear infinite;
    content: "";
    /* MSEdgeだとこ↑こ↓でcontentを設定しないと動作しませんでした。
       Chromium系ブラウザ・blinkやその他も同じだと思います。*/
}

これを活用するとJavaScript無しのストップウォッチみたいなのも作れます。

注意

animation属性・keyframeはトランジション的に変わるので、文字列を使うと

内部 状態 設定
0% 0%のテキスト 0%のテキスト
5% 10%のテキスト ←この中間点で変化していまう!
10% 10% 10%のテキスト

まあこんな感じに変化してしまうので
↓このようにずらすといいです。

内部 状態 設定
0% 0%のテキスト 0%のテキスト
5% 0%のテキスト 0%のテキスト
10% 10%のテキスト ←ここで変化!
15% 10%のテキスト 10%のテキスト
20% 20%のテキスト ←ここで変化!
25% 25%のテキスト 20%のテキスト

これらはウェブレンダリングエンジンによって変化タイミング等が違う可能性があります。ちゃんと確認しましょう。

まとめ

疑似要素とcontentanimation(@keyframes)の合わせ技でCSSだけで文字列を定期的に変化させられる!

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?