簡體   English   中英

如何在字符串中換行或從 html 中獲取帶有標簽純 JS 的字符串

[英]How to make a line break in a string or get a string from html with tags pure JS

我有一些這樣的代碼可以實現打字機效果。 我將標簽中的文本提取到 html 中,然后將其與效果一起粘貼回去。

唯一的一點是沒有考慮到<br>標簽,文本插入一行。

如何獲取文本以及標簽或從 JS 手動添加?

 var str = document.querySelector('.index-title-main h1').textContent || document.querySelector('.index-title-main h1').innerText, i = 0, isTag, text; (function type() { text = str.slice(0, ++i); if (text === str) return; document.querySelector('.index-title-main h1').style.display = 'inline'; document.querySelector('.index-title-main h1').innerHTML = text; var char = text.slice(-1); if( char === '<' ) isTag = true; if( char === '>' ) isTag = false; if (isTag) return type(); setTimeout(type, 80); }());
 body{ width: 100%; height: 100vh; background-color: #000; }.index-title-main{ color: #fff; font-size: 25px; height: 290px; white-space: pre-wrap; }
 <div class="index-title-main"><h1 style="display: none;">TEXT,<br>TEXT,<br>TEXT </h1></div>

如何將var str.textContent.innterText更改為.innerHTML

 var str = document.querySelector('.index-title-main h1').innerHTML, i = 0, isTag, text; (function type() { text = str.slice(0, ++i); if (text === str) return; document.querySelector('.index-title-main h1').style.display = 'inline'; document.querySelector('.index-title-main h1').innerHTML = text; var char = text.slice(-1); if( char === '<' ) isTag = true; if( char === '>' ) isTag = false; if (isTag) return type(); setTimeout(type, 80); }());
 body{ width: 100%; height: 100vh; background-color: #000; }.index-title-main{ color: #fff; font-size: 25px; height: 290px; white-space: pre-wrap; }
 <div class="index-title-main"><h1 style="display: none;"> TEXT,<br>TEXT,<br>TEXT </h1></div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM