【问题标题】:change the font of a string one character at a time一次更改一个字符的字符串的字体
【发布时间】:2017-06-08 20:11:31
【问题描述】:

如果我给每个字符自己的#id,我知道如何一次更改一个字符的字体样式,但是,我希望对整个网页都这样做。有没有更有效的方法?还是让数百个#ids 成为一个可行的选择?

<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 对象?这可能吗?

【问题讨论】:

  • 您可以使用text.split("") 来获取数组中的每个字符。无需编写for 循环。

标签: javascript jquery string text fonts


【解决方案1】:

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】:

    将文本转换为数组,对其进行迭代并将每个字符包装在&lt;span&gt;-tag 中,并为其应用一个指定字体的类。

    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";
    }
    

    【讨论】:

      猜你喜欢
      • 2010-11-16
      • 2015-04-20
      • 1970-01-01
      • 1970-01-01
      • 2016-05-09
      • 2014-04-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多