如何在脚本上添加新行

时间:2016-05-16 18:45:20

标签: javascript html css

您好我不知道我的标题是否有用,但这里是我的问题我想在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);
}());
&#13;
#typewriter {
		color: lime;
		text-align: center;
	}
&#13;
 <div id="typewriter"></div>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:1)

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>

答案 1 :(得分:0)

使用<br />

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

答案 2 :(得分:0)

另一种可能性是使用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>