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