如何在脚本上添加新行

How to add a new line on a script

本文关键字:添加 新行 脚本      更新时间:2023-09-26

你好,我不知道我的标题是否有帮助,但这是我的问题,我想在JS、CSS、HTML中创建一个类型编写器效果,除了添加一行新的文本外,其他一切都很好。

	var str = "<p>I want to put text here then another line under this one</p>",
	<!--var str = "<p>text here</p>",--> <!--This is what I tried to do to add a new line-->
    i = 0,
    isTag,
    text;
(function type() {
    text = str.slice(0, ++i);
    if (text === str) return;
    
    document.getElementById('typewriter').innerHTML = text;
    var char = text.slice(-1);
    if( char === '<' ) isTag = true;
    if( char === '>' ) isTag = false;
    if (isTag) return type();
    setTimeout(type, 80);
}());
#typewriter {
		color: lime;
		text-align: center;
	}
 <div id="typewriter"></div>

var str = "My text'nSome more text";
var stra = str.split("");
var tw = document.getElementById("output");
function type(){
   var char = stra.shift();
   if (char){
       tw.innerHTML += char;
       setTimeout(type, 80);
   }
 
}
type();
<pre id="output"></pre>

使用<br />

var str = "<p>I want to put text here<br /> then another line under this one</p>";

另一种可能性是使用span对paragragh元素进行分组,并将span的显示样式属性添加到块中。

window.onload = function () {
  var str = "<p><span>I want to put text here then another line under this one</span><span>text here</span></p>";
  (function type(isInTagArg, indexArg) {
    var index = indexArg || 0;
    if (index >= str.length)
      return;
    var isInTag = isInTagArg || false;
    if (isInTag == false) {
      if (str.charAt(index) == '<') {
        return type(true, index + 1);
      } else {
        document.getElementById('typewriter').innerHTML = str.substr(0, index + 1);
      }
    } else {
      if (str.charAt(index) == '>') {
        return type(false, index + 1);
      }
      return type(true, index + 1);
    }
    setTimeout(function() {type(false, index + 1)}, 80);
  }());
}
#typewriter {
  color: lime;
  text-align: center;
}
#typewriter span
{
  display: block;
}
<div id="typewriter"></div>