javascript - 用单个跨度作为字母替换文本的 div 并遍历它

标签 javascript

我试图用每个字母的单个 span 元素替换文本的 div,这很简单,但我试图让这些 span 字体大小逐渐增加,但我无法弄清楚在 setTimeout 函数中抛出什么。

<div id ="foo"> Welcome to Here </div> 

function test() {

  let word = document.getElementById('foo');
  let arr = word.split("")
  word.innerHTML = "";
  arr.forEach((x,index) => {
    let newSpan = document.createElement('span')
    newSpan.innerHTML = x;
    word.appendChild(newSpan);
    setTimeout(() => {
    ????
       }, 100 + index*100)

 })    
}

最佳答案

对元素的内部文本进行拆分并增加跨度的字体大小:

function test() {

  const baseFontSize = 16;                       // starting font size
  const word = document.getElementById('foo');
  const text = word.innerText;                   // split this and not your element object
  const arr = text.split("");
  
  word.innerHTML = "";
  arr.forEach((x, index) => {
    let newSpan = document.createElement('span')
    newSpan.innerHTML = x;
    word.appendChild(newSpan);
    
    setTimeout(function() {
	    newSpan.style.fontSize = (baseFontSize + (index * 2)) + 'px';  // increment by 2px
    }, 1000 * index)                                                 // increment each span a second after the last
  })
}

test();
<div id="foo">Welcome to Here</div>

关于javascript - 用单个跨度作为字母替换文本的 div 并遍历它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54220899/

相关文章:

javascript - 在javascript中执行命令

javascript - 当我使用 php include 时未定义 Js 函数

javascript - 复选框上的 Onclick 函数仍然有效,即使它被 JavaScript 替换为其他函数

javascript - 隐藏文本并在悬停时显示其他一些文本

javascript - 在动态创建的元素上单击时无法按预期工作 jQuery

javascript - 从子元素 jquery 中抓取文本

javascript - 你如何为游戏制作介绍屏幕

javascript - Instagram Api OAuthAccessTokenException 400 错误

javascript - 多系列图表——时间(年)区间x轴叠加多年数据

javascript - 如何在 SequelizeJS 中使用 $in 运算符?