溢出的输入文本

Overflowing input text

本文关键字:文本 输入 溢出      更新时间:2023-09-26

以下是JSFiddle演示:http://jsfiddle.net/qox0yxb4/

我使用type()来创建一个打字机效果(每个字符都打印在屏幕上,中间有一个延迟)。我使用addTextToScreen(textForScreen)向队列添加文本,然后通过type()将文本添加到屏幕上。当我从JavaScript中调用addTextToScreen()时,文本似乎是格式化的,因为它不会在x轴上溢出,但是当我接受来自HTML <input>标记(printText())的输入时,文本会在x轴溢出。

以下是JavaScript方法:

var i = 0,
isTag=false,
text;
var typeTime = 45;
function type() {
    if (text === textOnScreen){
      setTimeout(function(){type();}, typeTime);
      return;
    }
    text = textOnScreen.slice(0, i+1);
    i++;
    document.getElementById('paraText').innerHTML = text;
    var char = text.slice(-1);
    console.log(char);
    if( char === '<' ) isTag = true;
    if( char === '>' ) isTag = false;
    if (isTag) return type();
    setTimeout(function(){type();}, typeTime);
}
function addTextToScreen(textForScreen){
    textOnScreen = textOnScreen + textForScreen;
}
type();
function printText(event) {
   if(event.keyCode == 13){
        printText = document.getElementById("inputText").value.toString();
        addTextToScreen("<br>" + printText.toString());
        x = document.getElementById("inputText");
        x.value = "";
   }
}

我还注意到,每当我将文本粘贴到输入框中时(文本可以来自任何地方),它似乎是格式化的,并且不会溢出。

将此css属性添加到#paraText:

word-wrap:break-word;

JS Fiddle演示

Josh建议使用break-all,区别如下。

您缺少的神奇CSS规则是word-break: break-all;。再加上这个,它的工作原理就像你所期望的那样。

证明