WePuri
ワードプレス教室

WePuri
ワードプレス教室

MENU
[bogo]

テキストを1文字ずつspanで囲む

サンプルコード

spanでテキストを囲むパターン

<div id="box">テキスト</div>
'use strict';
{
    //#boxを指定
    const $box = document.getElementById('box');

    //#boxの中のテキストを配列として代入にする
    const $text = $box.textContent.split('');

    //#box内のテキストを1度削除する
    $box.textContent = '';
    
    //配列に入れたテキストを1文字ずつ吐き出し<span>で囲む
    for (let a = 0; a < $text.length; a++) {
        let $span = '<span>'+$text[a]+'</span>';
        $box.insertAdjacentHTML('beforeend' , $span)
    }
}

ボタンをクリックしたらテキストが横から出てくるパターン

<div id="btn">ここをクリック</div>
<div id="box">テキスト</div>
#btn{
    margin: 80px auto;
    width: 200px;
    height: 56px;
    display: flex;
    justify-content: center;
    align-items: center;
    background: #000;
    color: #fff;
    border-radius: 3em;
}
#box{
    font-size: 32px;
    font-weight: bold;
    color: rgb(33, 97, 180);
    text-align: center;
    span{
        display: inline-block;
        opacity: 0;
        transform: translateX(100px);
    }
}
#box.on{
    span{
        opacity: 1;
        transform: translateX(0);
    }
}
//テキストをspanで1文字ずつ囲む
const $box = document.getElementById('box');
const $text = $box.textContent.split('');
$box.textContent = '';
for (let a = 0; a < $text.length; a++) {
    b = ( a + 1 ) * 0.5;
    let $span = '<span style="transition:transform '+b+'s;">'+$text[a]+'</span>';
    $box.insertAdjacentHTML('beforeend' , $span);
}

//クリックしたらonを付与する
const $btn = document.getElementById('btn');
$btn.addEventListener('click' , () => {
    $box.classList.toggle('on');
});