简体   繁体   English

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

[英]Word wrap in multiline textbox after 35 characters

<asp:TextBox CssClass="txt" ID="TextBox1" runat="server"
             onkeyup="CountChars(this);" Rows="20" Columns="35" 
             TextMode="MultiLine" Wrap="true">
</asp:TextBox>

I need to implement word-wrapping in a multi-line textbox.我需要在多行文本框中实现自动换行。 I cannot allow users to write more then 35 chars a line.我不能允许用户每行写超过 35 个字符。 I am using the following code, which breaks at precisely the specified character on every line, cutting words in half.我正在使用以下代码,它在每一行的指定字符处精确中断,将单词减半。 Can we fix this so that if there's not enough space left for a word on the current line, we move the whole word to the next line?我们能否修复此问题,以便在当前行中没有足够的空间容纳单词时,将整个单词移至下一行?

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);
}

Edit - 1编辑 - 1

I have to show total max 35 characters in line without specific word break and need to keep margin of two characters from the right.我必须在没有特定分词符的情况下显示最多 35 个字符,并且需要从右边保留两个字符的边距。 Again, the restriction should be for 35 characters but need space for total 37 (Just for the Visibility issue.)同样,限制应为 35 个字符,但总共需要 37 个字符的空间(仅用于可见性问题。)

I use the following Jquery plugin in an asp.net web app.我在 asp.net web 应用程序中使用以下 Jquery 插件。 Put this code under the opening script tag:将此代码放在开始脚本标签下:

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);
}

And then in document ready add:然后在准备好的文档中添加:

$(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

And then on each textarea just ensure that maxlength='35' like so and add a feedback placeholder...然后在每个 textarea 上确保 maxlength='35' 像这样并添加一个反馈占位符......

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

Hope this helps!希望这可以帮助!

This is a testing exercise.这是一个测试练习。 This will break the line at 35 characters.这将在 35 个字符处换行。 Make sure to set cols="35"确保设置cols="35"

I hope this helps.我希望这有帮助。

UPDATE: 6/26/2012更新:2012 年 6 月 26 日

Removed my JSFiddle link.删除了我的 JSFiddle 链接。 I will not solve the problem unless you start to answer questions being asked by myself and others.除非你开始回答我自己和其他人提出的问题,否则我不会解决问题。

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

This code should wrap the text at 35 characters like you need.此代码应按照您的需要将文本换行为 35 个字符。 This is kind of a weird way to restrict input but it should work.这是一种限制输入的奇怪方式,但它应该有效。 (Previous versions had bugs in them.. I think this one finally works for the most part) (以前的版本中有错误。我认为这个版本最终在大部分情况下都有效)

Taking JakeJ's comment a step further,让 JakeJ 的评论更进一步,

If having more than 35 characters on a line would break something, it's not such a good idea to do javascript validation.如果一行中超过 35 个字符会破坏某些东西,那么进行 javascript 验证就不是一个好主意。 You may encounter issues where someone has javascript disabled, or knows how to break the check if they're being malicious.您可能会遇到有人禁用了 javascript 的问题,或者如果他们是恶意的,则知道如何破坏检查。 Is it a possibility to do this server side?是否有可能在服务器端执行此操作? Perhaps a little information on why you need this and we could help with a possible alternate solution?也许是关于您为什么需要这个的一些信息,我们可以帮助您提供可能的替代解决方案?

  • If it is important for the business logic that each line has no more than 35 characters, you definitely have to do it on the server.如果每行不超过 35 个字符对于业务逻辑很重要,那么您肯定必须在服务器上执行此操作。 You can only use JavaScript to improve the user interface.您只能使用 JavaScript 来改进用户界面。 But JavaScript will not protect your server-side logic from "illformed" inputs.但是 JavaScript 不会保护您的服务器端逻辑免受“格式错误”的输入。

  • For the presentation you can use the suggestion you already got from all the others and restrict the size of the input field to 35 columns.对于演示文稿,您可以使用您已经从所有其他人那里得到的建议,并将输入字段的大小限制为 35 列。 This will not change the input value sent to the server, but you will have to do that on the server anyway.这不会更改发送到服务器的输入值,但无论如何您都必须在服务器上执行此操作。 Like you correctly noticed, in newer browsers the users can re-size the textarea.正如您正确注意到的那样,在较新的浏览器中,用户可以重新调整文本区域的大小。 This is completely web-like: The user gets the power to adjust the presentation according to their flavor.这完全类似于网络:用户可以根据自己的喜好调整呈现方式。 If - and only if - you really need to restrict that because there is business logic behind, you can disable the re-sizing feature .如果——且仅当——你真的需要限制它,因为背后有业务逻辑,你可以禁用调整大小功能

  • If it is not important for the business logic but only a matter of presentation then you definitely want to use plain styling instead: Use a 35-columns sized text area and leave it up to the user to resize it.如果它对业务逻辑不重要而只是表示问题,那么您肯定想使用普通样式:使用 35 列大小的文本区域并让用户调整它的大小。

Remarks:评论:

  • Be aware that if you wrap lines using JavaScript by adding line breaks, you will cope with the use case that the user changes lines that were already wrapped.请注意,如果您通过添加换行符使用 JavaScript 换行,您将应对用户更改已换行的用例。 Do you re-merge and re-wrap them, or will they just become more and more ugly?您是重新合并并重新包装它们,还是它们会变得越来越丑陋? With the approach I just mentioned you will not have to cope with that.使用我刚才提到的方法,您将不必处理这些问题。 Try the jsfiddle posted by Brett Holt .试试Brett Holt 发布的 jsfiddle Write some text until it wraps.写一些文字直到它换行。 Then go back to the first line and delete some characters (use backspace, the delete key did not work for me using FireFox).然后回到第一行并删除一些字符(使用退格键,删除键对我使用 FireFox 不起作用)。 You will see what I mean.你会明白我的意思。 The user will have to be able to remove the original wrapping and have your application re-wrap the line at a different position.用户必须能够移除原来的换行,并让您的应用程序在不同的位置重新换行。

  • By default textareas have a fixed-width font so each line will be restricted to 35 characters regardless of whether it is an "m" or an "l".默认情况下,textareas 具有固定宽度的字体,因此每行将被限制为 35 个字符,无论它是“m”还是“l”。 But you may want to be on the safe side and set the font to a fixed in CSS in addition.但是您可能希望安全起见,另外在 CSS 中将字体设置为固定字体。

  • For the "2 blank" requirement - that just sounds silly to me, honestly.对于“2 个空白”的要求——老实说,这对我来说听起来很愚蠢。 Take what the browser does for you.以浏览器为您做的事情为例。 It works for all other websites and web applications.它适用于所有其他网站和网络应用程序。 Use CSS to style it (consider adding a padding, for example) but please do not start to add JavaScript hacks.使用 CSS 对其进行样式设置(例如,考虑添加填充)但请不要开始添加 JavaScript 技巧。 If the requirement is from your client, I am sure you can talk to them and explain why it does not work well the way they wanted.如果要求来自您的客户,我相信您可以与他们交谈并解释为什么它不能按照他们想要的方式工作。

Thanks for all of the examples.感谢所有的例子。 I worked on this, because ultimately I need to wordwrap text in an SVG xml (which my current spec. doesn't support word-wrapping).我致力于此,因为最终我需要在 SVG xml 中对文本进行自动换行(我当前的规范不支持自动换行)。

Here is my edit too.这也是我的编辑。 https://jsfiddle.net/vr_driver/7kr1vfq5/50/ 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>

Here is a simple function that breaks the lines at (or before) 35 characters.这是一个简单的函数,它在 35 个字符处(或之前)换行。 The only scenario this would currently fail for is if you have more than 35 characters with no space.目前唯一会失败的情况是,如果您有超过 35 个字符且没有空格。 If you want a hard-break in this scenario let me know and I'll add that in.如果您想在这种情况下进行硬破解,请告诉我,我会添加进去。

You can see it working over on JS Fiddle - just hit GO to see the result.你可以看到它在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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM