0

我正在尝试使用一个简单的 jquery 打字机来识别像 \n 和 \r 这样的空白字符,以便生成的文本实际上会有换行符。当我尝试让控制结构识别“\”时,根本没有运行...任何帮助表示赞赏!

<html>
<head>

<script type="text/javascript" src="jquery.js"></script>

<script type="text/javascript">

    var text = "runtype";
    var count = 0;
    var maxspeed = 200;

    $(document).ready(function() {

      function typeit(userInput) {
        text = userInput;
        type();
      }

      function character(start, end, text) {
        return text.substring(start, end);
      }

      function type(){

        var random = Math.floor(Math.random() * maxspeed);
        var char1 = character(count, count+1, text);
        var char2 = character(count+1, count+2, text);
        var whitespace = char1+char2;

        if (char1 === '\\'){
          $('#box').append(whitespace);
          setTimeout(type, 20);
        } else if (char1 === ' '){
          $('#box').append(char1);
          setTimeout(type, 20);
        }else if (char1 === '@'){
          ;
          setTimeout(type, 300);
        } else {
          $('#box').append(char1);
          setTimeout(type, random);
        }

        count++;

    }

    typeit('runtype and \\nruntype and runtype');
    });

</script>

</head>
<body>
<div id="box"></div>

</body>
</html>
4

3 回答 3

1

whitespace is the literal string \n ("\\n", two characters), not a linebreak. You would need to append an actual whitespace (if that appears because of CSS white-space: pre-wrap) or use a <br/> element or create a new paragraph.

于 2013-09-23T16:18:28.510 回答
1

当您直接附加到 DOM 时,空格将不起作用(除了添加一个空格)。相反,您需要附加一个元素来强制换行。在此示例中,当在输入字符串中遇到abr时,我使用了一个标记:\n

if (char1 === '\\') {
    if (char2 === 'n') {
        $('#box').append('<br />');
        count++; // to cover the second character of the chord
    }
    /*
    if (char2 === 'something else') {
        More logic for other chords. 
        Could possibly changed to a switch if you've got lots of options.
    }
    */
    setTimeout(type, 20);
} 

示例小提琴

于 2013-09-23T16:16:43.050 回答
1

正如其他答案所指出的,默认情况下,html 中会忽略空格中的新行。

这是您的示例的jsFiddle修改以替换\n<br/>以生成新行(在方法调用中,您必须只使用 single \,以便将\n其识别为换行符,如果您使用\\n,那么您将反斜杠转义为反斜杠)。

另一种选择是使用jsFiddlewhite-space: pre-wrap;中所示的css 样式设置您的输出。

于 2013-09-23T16:37:23.490 回答