在 35 个字符后的多行文本框中自动换行

Word wrap in multiline textbox after 35 characters

本文关键字:文本 自动换行 字符      更新时间:2023-09-26
<asp:TextBox CssClass="txt" ID="TextBox1" runat="server"
             onkeyup="CountChars(this);" Rows="20" Columns="35" 
             TextMode="MultiLine" Wrap="true">
</asp:TextBox>

我需要在多行文本框中实现自动换行。我不能允许用户一行写超过 35 个字符。我使用以下代码,它精确地在每行的指定字符处中断,将单词切成两半。我们是否可以解决此问题,以便如果当前行上没有足够的空间容纳某个单词,我们将整个单词移动到下一行?

function CountChars(ID) {
    var IntermediateText = '';
    var FinalText = '';
    var SubText = '';
    var text = document.getElementById(ID.id).value;
    var lines = text.split("'n");
    for (var i = 0; i < lines.length; i++) {
        IntermediateText = lines[i];
        if (IntermediateText.length <= 50) {
            if (lines.length - 1 == i)
                FinalText += IntermediateText;
            else
                FinalText += IntermediateText + "'n";
        }
        else {
            while (IntermediateText.length > 50) {
                SubText = IntermediateText.substring(0, 50);
                FinalText += SubText + "'n";
                IntermediateText = IntermediateText.replace(SubText, '');
            }
            if (IntermediateText != '') {
                if (lines.length - 1 == i)
                    FinalText += IntermediateText;
                else
                    FinalText += IntermediateText + "'n";
            }
        }
    }
    document.getElementById(ID.id).value = FinalText;
    $('#' + ID.id).scrollTop($('#' + ID.id)[0].scrollHeight);
}

编辑 - 1

我必须在没有特定分词符的情况下显示总共最多 35 个字符,并且需要保持右侧两个字符的边距。同样,限制应为 35 个字符,但总共需要 37 个字符的空间(仅用于可见性问题。

http://jsfiddle.net/g4Kez/4/

此代码应根据需要将文本换行为 35 个字符。这是一种限制输入的奇怪方式,但它应该有效。(以前的版本有错误。我认为这个终于在大多数情况下起作用了)

我在 asp.net Web 应用程序中使用以下 Jquery 插件。 将此代码放在开始脚本标记下:

jQuery.fn.limitMaxlength = function(options){
var settings = jQuery.extend({
attribute: "maxlength",
onLimit: function(){},
onEdit: function(){}
}, options);
// Event handler to limit the textarea
var onEdit = function(){
var textarea = jQuery(this);
var maxlength = parseInt(textarea.attr(settings.attribute));
if(textarea.val().length > maxlength){
  textarea.val(textarea.val().substr(0, maxlength));
  // Call the onlimit handler within the scope of the textarea
  jQuery.proxy(settings.onLimit, this)();
}
// Call the onEdit handler within the scope of the textarea
jQuery.proxy(settings.onEdit, this)(maxlength - textarea.val().length);
}
this.each(onEdit);
return this.keyup(onEdit)
    .keydown(onEdit)
    .focus(onEdit);
}

然后在文档就绪中添加:

$(document).ready(function () {
//give the user feedback while typing
var onEditCallback = function(remaining){
$(this).siblings('.charsRemaining').text("Characters remaining: " + remaining);
if(remaining > 0){
    $(this).css('background-color', 'white');
    }
}
var onLimitCallback = function(){
    $(this).css('background-color', 'red');
}
$('textarea[maxlength]').limitMaxlength({
    onEdit: onEditCallback,
    onLimit: onLimitCallback
});
});//end doc ready

然后在每个文本区域上,只需确保 maxlength='35' 就像这样并添加一个反馈占位符......

<textarea id="TextBox1" class="txt" runat="server" placeholder="Some Text"  maxlength="35" cols="35" rows="2" ></textarea>

希望这有帮助!

这是一个测试练习。这将在 35 个字符处换行。确保设置cols="35"

我希望这有所帮助。

更新日期: 6/26/2012

删除了我的JSFiddle链接。除非你开始回答我和其他人提出的问题,否则我不会解决问题。

将JakeJ的评论更进一步,

如果一行超过 35 个字符会破坏某些内容,那么进行 javascript 验证并不是一个好主意。您可能会遇到有人禁用了 javascript 的问题,或者知道如何在他们恶意时中断检查。是否可以做这个服务器端?也许有一些关于您为什么需要它的信息,我们可以帮助您提供可能的替代解决方案?

  • 如果每行不超过 35 个字符对于业务逻辑很重要,那么您肯定必须在服务器上执行此操作!您只能使用 JavaScript 来改进用户界面。但是 JavaScript 不会保护你的服务器端逻辑免受"格式错误"输入的影响。

  • 对于演示文稿,您可以使用已从所有其他演示文稿中获得的建议,并将输入字段的大小限制为 35 列。这不会更改发送到服务器的输入值,但无论如何您都必须在服务器上执行此操作。就像您正确注意到的那样,在较新的浏览器中,用户可以调整文本区域的大小。这完全像网络:用户可以根据自己的口味调整演示文稿。如果 - 并且仅当 - 您确实需要限制它,因为背后有业务逻辑,您可以禁用重新调整大小功能。

  • 如果它对业务逻辑重要,而只是表示问题,那么您肯定希望改用纯样式:使用 35 列大小的文本区域,并将其留给用户调整其大小。

言论:

  • 请注意,如果您通过添加换行符来使用 JavaScript 换行,您将处理用户更改已换行的行的用例。你是重新合并并重新包装它们,还是它们会变得越来越丑陋?使用我刚才提到的方法,您将不必应对这种情况。试试Brett Holt发布的jsfiddle。写一些文本直到它换行。然后回到第一行并删除一些字符(使用退格键,删除键对我使用 Firefox 不起作用)。你会明白我的意思。用户必须能够删除原始换行,并让应用程序在不同的位置重新换行。

  • 默认情况下,文本区域具有固定宽度的字体,因此每行将限制为 35 个字符,无论它是"m"还是"l"。但是为了安全起见,您可能希望另外在CSS中将字体设置为固定字体。

  • 对于"2 空白"要求 - 老实说,这对我来说听起来很愚蠢。以浏览器为您执行的操作为例。它适用于所有其他网站和 Web 应用程序。使用CSS来设置它的样式(例如,考虑添加填充),但请不要开始添加JavaScript黑客。如果要求来自您的客户,我相信您可以与他们交谈并解释为什么它不能按照他们想要的方式很好地工作。

感谢所有的例子。我为此努力,因为最终我需要在 SVG xml 中自动换行文本(我当前的规范不支持自动换行)。

这也是我的编辑。https://jsfiddle.net/vr_driver/7kr1vfq5/50/

function columncorrector() {
  var text = document.getElementById("TextBox1").value;
  var maxcolumnwidth = 40;
  var lengthSinceNewLine = function(input) {
    var lastNewLine = input.lastIndexOf("'n");
    if (lastNewLine == -1) {
      return input.length;
    } else {
      console.log("lnl: " + lastNewLine);
      console.log("input.length: " + input.length);
      return input.length - lastNewLine;
    }
  };
  console.log(lengthSinceNewLine(text));
  lines = text.split("'n").length;
  console.log("lines: " + lines);
  if (lines == 1) // without this, the first line always comes out one character longer
  {
    maxcolumnwidth_fix = maxcolumnwidth - 2;
  } else {
    maxcolumnwidth_fix = maxcolumnwidth - 1;
  }
  if (lengthSinceNewLine(text) >= maxcolumnwidth_fix) {
    if (text[text.length - 1] == " ") {
      text = text + "'n";
    } else {
      console.log("length:" + text.length);
      console.log(text.lastIndexOf(" "));
      if (text.lastIndexOf(" ") == "-1") {
        console.log("here 1");
        text = text + "-'n"; // a forced hyphen            
        document.getElementById("TextBox1").value = text;
      } else {
        var space = text.lastIndexOf(" ");
        text = text.substring(0, space) + "'n" + text.substring(space + 1, text.length);
        document.getElementById("TextBox1").value = text;
      }
    }
  }
};
.txt {
  width: 400px;
}
<textarea id="TextBox1" class="txt" rows="30" onkeydown="columncorrector()" onkeyup="columncorrector()"></textarea>

这是一个简单的函数,可以在 35 个字符处(或之前)换行。目前唯一会失败的情况是,如果字符超过 35 个且没有空格。如果您想在这种情况下进行硬突破,请告诉我,我会添加它。

你可以看到它在JS Fiddle上工作 - 只需点击GO即可查看结果。

var breakLines = function () {
    var i, limit = 35, lines = [], result = '', currentLine = '';
    var textBox = document.getElementById('example');
    var text = textBox.value;
    var words = text.split(' ');
    for (i = 0; i < words.length; i++) {
        var extendedLine = currentLine + ' ' + words[i];
        if (extendedLine.length > limit) {
            lines.push(currentLine);
            currentLine = words[i];
        } else {
            currentLine = extendedLine;
        }
    }
    if (currentLine.length > 0) {
        lines.push(currentLine);
    }

    for (i = 0; i < lines.length; i++) {
        result += lines[i] + ''r'n';
    }
    textBox.value = result;
};
<script type="text/javascript">
    function CountChars(ID) {
        var IntermediateText = '';
        var FinalText = '';
        var SubText = '';
        var Splitted;
        var Concatenated;
        var text = document.getElementById(ID.id).value;
        var lines = text.split("'n");
        for (var i = 0; i < lines.length; i++) {
            IntermediateText = lines[i];
            if (IntermediateText.length <= 50) {
                if (lines.length - 1 == i)
                    FinalText += IntermediateText;
                else
                    FinalText += IntermediateText + "'n";
            }
            else {
                Splitted = IntermediateText.split(' ');
                for (var index = 0; index < Splitted.length; index++) {
                    Concatenated = Splitted[index].length;
                    if (Concatenated + SubText.length <= 50) {
                        if (index + 1 != Splitted.length) {
                            SubText += Splitted[index] + " ";
                        }
                        else {
                            SubText += Splitted[index];
                        }
                    }
                    else {
                        FinalText += SubText + "'n";
                        SubText = "";
                        if (index + 1 != Splitted.length) {
                            SubText = Splitted[index] + " ";
                        }
                        else {
                            SubText = Splitted[index];
                        }
                    }
                }
                if (SubText != '') {
                    FinalText += SubText;
                }
            }
        }
        document.getElementById(ID.id).value = FinalText;
        $('#' + ID.id).scrollTop($('#' + ID.id)[0].scrollHeight);
    }
</script>

<asp:TextBox ID="txt" onkeyup="CountChars(this);" Width="60%" runat="server" Rows="20"
                    Columns="50" TextMode="MultiLine" MaxLength="1000"></asp:TextBox>