2017-01-24 8 views
3

各文字に#idを付けると、一度にフォントスタイルを変更する方法がわかりますが、全ウェブページでこれをやりたいと思います。もっと効率的な方法がありますか?または何百もの#IDを実行可能なオプションにしていますか?文字列のフォントを一度に1文字ずつ変更する

<body> 
    <div> 
     <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit...</p> 
    </div> 

    <script src="jquery.js" type="text/javascript" ></script> 

    <script> 
     var text = $("p").text(); 
     var newText = []; 
     for (var i = 0; i < text.length; i++) { 
      newText.push(text[i]); 
      // ???????? function goes here ???????? 
     } 
    </script> 
</body> 

最終的に、各文字列をHTMLオブジェクトにする必要があると思いますか?これは可能ですか?

+0

'text.split(" "") 'を使用すると、配列内の各文字を取得できます。 'for'ループを書く必要はありません。 – tanmay

答えて

0

HTML

<h1 id='name'>HULK IS GETTING ANGRY</h1> 

JS

$(document).ready(function(){ 
    var name = $('#name').text(); 
    var i = 0; 

    function changeColor() { 
    setTimeout(function() { 
     var firstPart = name.substr(0,i); 
     var secondPart = name.substr(i,name.length); 
     var newHtml = '<span style="color:green; font-family: \'Comic Sans MS\';">'+firstPart+'</span>'+secondPart; 

     if (i < name.length) { 
     changeColor(); 
     } 
     i++; 
    }, 500); 
    } 
    changeColor(); 
}); 

Check out this code-pen snippet

2

テキストを配列に変換し、それを反復処理して<span>タグ内のすべての文字をラップし、そのフォントを指定するクラスを適用します。

var text = $('p').text().split(''); 

text = text.map(function (char) { 

    // you probably don't want to wrap spaces 
    if (char === ' ') { 
     return char; 
    } 

    return '<span class="comicSans">'+char+'</span>'; 
}); 

// convert the array back into a string 
text = text.join(''); 

// replace the original string with the new 'fancy' string 
$('p').text(text); 

のstyle.css

.comicSans { 
    font-family: "Comic Sans"; 
} 
関連する問題