目次
Javascriptで文字をオサレに登場させてみる
Javascriptは、Webブラウザ上でうごく言語で、ホームページ作成では、HTML、CSS、Javascriptの3つが基本となっています。
ごろうは、Vuejsを使ったことがあったので構文はなんとなく理解しやすいですが、Web特有の要素取得があるところが初めての経験です。
リセットCSSという存在を知る
ブラウザ事で余白や表示がことなるところがあるので、どのブラウザでも同じように表示するために、リセット用のCSSを適用することが基本とのこと。
ごろうは、レベルが1上がった✊
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<!-- リセットCSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/destyle.css@1.0.15/destyle.css" />
<link rel="stylesheet" href="./common.css">
<script src="main.js" defer></script>
</head>
今回は、リセットCSSをCDNで導入してみました。
Javascriptでタグを一文字ごとにつける
一文字ごとにアニメーションをつけようと思うと、一文字ごとにタグをつけていくことになりますが、そうすると変更があった時にも大変ですし、HTMLコードも長くなってしまいます。
そこでJavascriptで文字列に合わせてタグをつけるようにしていきます。
<body>
<main>
<div class="text-animation">食べカフェ</div>
<div class="text-animation">pu-a-pu</div>
</main>
</body>
@charset "utf-8";
@import url('https://fonts.googleapis.com/css2?family=Kiwi+Maru:wght@300&display=swap');
*, *::before, *::after {
box-sizing: border-box;
}
body {
/* googlefontを適用 */
font-family: 'Kiwi Maru', serif;
/* 文字間調整 */
letter-spacing: 0.4em;
}
main {
/* デバイス毎の表示領域100% */
height: 100vh;
/* 背景色 */
background-color: black;
/* flex指定 */
display: flex;
/* 縦並び指定 */
flex-direction: column;
/* 中央寄せ左右 */
text-align: center;
/* 中央寄せ上下 */
justify-content: center;
}
.text-animation {
/* 文字色 */
color: white;
font-size: 60px;
}
/* https://qiita.com/manabuyasuda/items/86f9bf68f80ad7ce5104 */
/* クラス名での要素順指定 */
.text-animation:not(:first-of-type) {
margin-top: 20px;
}
.text-animation span {
/* kfs指定 */
animation-name: animation-span;
/* アニメーション時間 */
animation-duration: 3s ;
/* 初期は0%から開始backwards */
animation-fill-mode:backwards;
/* translate適用のためブロック要素に変更 */
display: inline-block;
animation-timing-function: cubic-bezier(0.25, 0.1, 0.14, 1.48);
}
@keyframes animation-span {
0% {
opacity: 0;
/* 初期をしたにずらす */
transform: translateY(20px);
}
100% {
opacity: 1;
}
}
CSSの中で、クラス名のなかで初めてのや、最後に適用するといった処理をするための、.text-animation:not(:first-of-type)で、テキスト毎の間を調整しています。
こうすることによって、2行目以降の上側にのもスペースが適用されることになります。
// クラス名を指定して要素を取得する
const animationText = document.querySelectorAll(".text-animation");
// アニメーションテキストを順番に処理する
for (let i = 0; i < animationText.length; i++) {
// i番目の要素を取得する
const targetText = animationText[i];
texts = targetText.textContent;
textsArray = [];
// テキストをクリアする
targetText.textContent = "";
// 文字数分くりかえす
for (let j = 0; j < texts.split("").length; j++) {
// 配列に追加していく
textsArray.push('<span style="animation-delay: ' + (0.2 * j) + 's">' + texts.split("")[j] + '<span>')
}
// 最後にinnerHTMLで反映
for (let k = 0; k < textsArray.length; k++) {
targetText.innerHTML += textsArray[k]
}
}
コメント