题解 | #文字输出#
文字输出
http://www.nowcoder.com/practice/b403d1051e5d4568912e6d265e1e2cde
function output(str) { var strArr = str.split('') //3 var blinkEl = document.getElementById('jsBlink') var children = blinkEl.parentNode.children var length = children.length for (var i = length - 2; i >= 0; i--) { children[i].parentNode.removeChild(children[i]) } console.log(blinkEl.parentNode) //2 var spanFactory = function (s) { var el = document.createElement('span') el.classList.add('word') el.classList.add('color' + (Math.floor(Math.random() * 24) + 1)) el.innerHTML = s return el } //1 var time = function () { if (strArr.length === 0) return var s = strArr.shift() if (s === '\n') { blinkEl.parentNode.insertBefore( document.createElement('br'), blinkEl ) } else { if ([' ', '<', '>'].includes(s)) { s = { ' ': ' ', '<': '<', '>': '>' }[s] } blinkEl.parentNode.insertBefore(spanFactory(s), blinkEl) } timer = setTimeout(time, 200) } time() }
测试用例有问题(Math.floor(Math.random() * 24) + 1)