【GSAP】転がるテキストに時間差出現を組み合わせる【デモあり】

今回はHTML・CSS・JavaScript(GSAP)を使用して転がるテキストに時間差出現を組み合わせてお洒落な実装をしてみました!

コピペしてすぐに実装できるようにCodePenによるデモを用意しています。お洒落なサイトなどでも使えそうなものとなっています。ぜひ最後までご覧いただけると嬉しいです。

1.実装イメージ

実装イメージは以下の通りです。

See the Pen TextRollOver + gsap by りょーすけ (@s_ryosuke_1242) on CodePen.

注意点としては予め、CDNでプラグインをダウンロードしておきましょう。

CDNはコチラ

必要なファイルは『gsap.min.js』です。

2.HTML

HTMLはコチラの通りになっています。比較的シンプルですね

<section class="animation-area">
  <div class="text-wrapper">
    <h1 data-text="転がるテキスト">
      <span class="text-inner">Text RollOver</span>
    </h1>
  </div>
</section>

3.CSS

次にCSSです。

*{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}
html,body,main,section{
    width: 100%;
}
.animation-area{
    width: 100%;
    height: 100vh;
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;
}
.text-wrapper {
	display: inline-block;
	margin: 0 1em;
}
.text-wrapper span{
	display: inline-block;
}
.text-wrapper h1 {
	position: relative;
	display: inline-block;
	padding: .1em 1em;
	color: #333;
	font-weight: 500;
    font-size: 8vw;
	line-height: 1;
	text-decoration: none;
	overflow: hidden;
}
.text-wrapper h1::after {
	position: absolute;
	top: 0;
	left: 0;
	content: attr(data-text);
	display: block;
	width: 100%;
	padding: .2em 0;
	transition: .3s ease-in-out;
	transform: translateY(2em);
    text-align: center;
}
.text-wrapper h1 .text-inner {
	display: inline-block;
	transition: .3s ease-in-out;
}
.text-wrapper h1:hover::after,
.text-wrapper h1:focus::after {
	transform: translateY(0);
}
.text-wrapper h1:hover .text-inner,
.text-wrapper h1:focus .text-inner {
	transform: translateY(-2em);
}

4.JavaScript

次にJavaScriptです

function txtSplit(el){
  var content = el.textContent;
  var text = content.trim();
  var newHtml = "";

  text.split("").forEach(function(v) {
      newHtml += "" + v + "";
  });
  el.innerHTML = newHtml;
}

var txtsplit = document.querySelector('.text-wrapper span');

txtSplit(txtsplit);

const textInner = document.querySelector('.text-inner');

gsap.from(textInner.querySelectorAll('span'),{
  stagger:{each:0.05},
  y:'120%',
  duration:.5
})