Javascript 将文本的div替换为单个跨距(如字母)并对其进行迭代

Javascript 将文本的div替换为单个跨距(如字母)并对其进行迭代,javascript,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.forE

我试图用每个字母的单个
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)

 })    
}
欢迎来到这里
功能测试(){
让word=document.getElementById('foo');
设arr=word.split(“”)
word.innerHTML=“”;
arr.forEach((x,索引)=>{
让newSpan=document.createElement('span'))
newSpan.innerHTML=x;
word.appendChild(newSpan);
设置超时(()=>{
????
},100+指数*100)
})    
}

此代码的问题在于
getDocumentById()
将返回对元素的引用,而不是文本本身

如果div的内部内容是纯文本,那么可以尝试以下方法

var domElement = document.getElementById('foo');
var word = domElement.innerText; // Here you get the text itself
domElement.innerText = ''; // Here you clear the previous content which should be text
for (let i = 0; i < word.length; i++) {
  var spanElement = document.createElement('span');
  spanElement.innerText = word[i];
  domElement.appendChild(spanElement);
}

他又一次尝试了

功能测试(){
var-fontSize=12;
让word=document.getElementById('foo');
设arr=word.innerHTML.split(“”)
word.innerHTML=“”;
arr.forEach((x,索引)=>{
变量fs=(fontSize+索引)+“px”;
让newSpan=document.createElement('span'))
newSpan.innerHTML=x;
word.appendChild(newSpan);
setTimeout(函数(){
newSpan.style.fontSize=fs
},2000+(指数*100));
})    
}
test()
span{
显示:内联块;
字号:12 ;;
}

欢迎来到这里
对元素的内部文本进行拆分,并增加span的字体大小:

功能测试(){
const baseFontSize=16;//开始字体大小
const word=document.getElementById('foo');
const text=word.innerText;//拆分此对象,而不是您的元素对象
const arr=text.split(“”);
word.innerHTML=“”;
arr.forEach((x,索引)=>{
让newSpan=document.createElement('span'))
newSpan.innerHTML=x;
word.appendChild(newSpan);
setTimeout(函数(){
newSpan.style.fontSize=(baseFontSize+(索引*2))+'px';//增量为2px
},1000*index)//在最后一个跨距之后的第二个跨距递增
})
}
test()

欢迎来到这里
函数返回对DOM元素的引用,而不是对其文本内容的引用。为什么需要设置超时?你不能只做
word.innerText.split(“”
)就可以了吗?@Pete我正试图一次一个地增加每个字母的字体大小,为什么不在span上添加一个样式属性呢?-我一次递增2px就是为了让你能看到它better@Pete有点像JSFIDLE,但我希望第一个字母先递增,然后是第二个字母,等等。这就是为什么我想使用timeoutThank,但是如果我想按顺序递增fontSize呢。我希望第一个跨度递增,然后是下一个跨度,等等。这就是为什么我想使用setTimeOutThank@alen。我想让字母一次增加一个大小,这就是为什么我想用一个超时来改变第一个字母,然后是第二个字母,等等,这就是我想要的。现在有道理了。非常感谢。嘿,皮特。。如果我在添加到div之前设置了setTimeout,会有什么不同吗?该死的,我也让fix在晚些时候发布了它:),但我希望它仍然很重要
spanElement.style.fontSize = i