繁体   English   中英

如何限制textarea中每行的字符数?

[英]How to restrict number of characters per line in textarea?

我有一个Ext JS TextArea。 我想在每行中将我的字符限制为15个字符,总行数不应超过10个。

我在这里要做的是

function(){
    var myValue = this.getValue();
    var myValueData = myValue.split(/\r*\n/);
    myValueData.length = 10;    
}

理想情况下,它应该省略第10行之后的所有行,但不会发生。 另外如何限制每行最多15个字符?

你可以尝试一下,但不是完美的,但应该有效。

也许更好的是使用更改侦听器,覆盖组件上的setValue或setRawValue函数。

https://fiddle.sencha.com/#view/editor&fiddle/2js1

   {
                xtype: 'textareafield',
                grow: true,
                name: 'message',
                fieldLabel: 'Message',
                anchor: '100%',
                listeners: {
                    change: function (cmp, newVal, oldVal) {
                        var arrayForEachLine = newVal.split(/\r\n|\r|\n/g);
                        var newVal = [];
                        Ext.Array.each(arrayForEachLine, function (line, index) {
                            if (line.length >= 10) {
                                offset = line;
                                while (offset.length > 0) {
                                    newVal.push(offset.substring(0, 10));
                                    offset = offset.substring(10);
                                }

                            } else {
                                newVal.push(line);
                            }
                            if (index === 10) return false;
                            if (newVal.length >= 10) {
                                newVal = newVal.slice(0, 10);
                                return false;
                            }
                        });
                        cmp.suspendEvent('change');
                        cmp.setValue(newVal.join('\n'));
                        cmp.resumeEvent('change');
                    }
                }
            }

这可以通过使用更改侦听器来实现。 我创建了一个演示(小提琴) 请查看小提琴,因为代码很整洁,也有评论。 请查看下面的更改侦听器代码:

listeners: {
                change: function () { 
                    var myValue = Ext.getCmp('myField').getValue(); 
                    var lines = myValue.split("\n"); 
                    if (lines.length > 10) { 
                        alert("You've exceeded the 10 line limit!"); 
                        Ext.getCmp('myField').setValue(textAreaValue); 
                    } else { //if num of lines <= 10
                        for (var i = 0; i < lines.length; i++) { /
                            if (lines[i].length > 15) { /
                                alert("Length exceeded in line " + (i+1)); 
                                Ext.getCmp('myField').setValue(textAreaValue); 
                            } else if (lines[i].length <= 15 && i == lines.length - 1) { 
                                textAreaValue = myValue; 
                            }

                        }
                    }

                }
            }

如果这个答案解决了你的问题,请将此标记为答案,因为这也将有助于其他人。 如果这个答案有任何问题,请在评论中告诉我。 如果出现问题,我很抱歉,因为我不是极端专家。 但我还是试过。

要限制textarea字符长度,可以使用以下属性maxlength。

<textarea maxlength="50">

截断字符串或​​数字。

text_truncate = function(str, length, ending) {
if (length == null) {
  length = 100;
}
if (ending == null) {
  ending = '...';
}
if (str.length > length) {
  return str.substring(0, length - ending.length) + ending;
} else {
  return str;
}
};

你可以叫它

text_truncate(yourContentToTruncate,15);

这个问题对正则表达式来说是完美的...

我的解决方案侧重于“最大字符宽度”“最大行数”要求,由于包装在单词上,我认为这些要求与“最大字符数”不同 因为这个解决方案使用普通的正则表达式,所以最好使用带有换行符的纯文本\\n来换行而不是html。

这个函数是幂等的,这意味着它的输出可以毫无问题地输入到它的输入中。 它也非常有效,因为它是纯正的正则表达式。 这两个属性都非常适合放入onchange处理程序来更新每个按键上的文本而不会导致大的性能损失。

const fit = (str, w = 80, h = 24) => {
    w = new RegExp(`(?![^\\n]{1,${w}}$)([^\\n]{1,${w}})\\s`, 'g');
    str = str.replace(w, '$1\n');
    h = new RegExp(`(((^|\\n)[^\\n]*){${h}})((($|\\n)[^\\n]*)+)`);
    str = str.replace(h, '$1');
    return str;
};

这个函数将字符串格式化为给定的宽度/高度,但它以非常令人愉快的方式进行:包装正则表达式考虑了现有的新行,这就是为什么它是幂等的,并且在不通过它们的单词之间打破了行。 有关word包装正则表达式如何工作以及为什么它是健壮的的深入解释,请参阅我的回答,在JavaScript中使用正则表达式自动换行字符串:

用JavaScript包装文本

此解决方案使用纯JavaScript。

基本思想是使用.match(/.{1,10}/g) 创建由15个字符组成的块数组,然后使用换行符 join("\\n") 连接数组以再次创建字符串。 仅使用splice(10, chunks.length - 1)删除剩余的块来限制行数。

我们正在使用.onkeyup事件,但可能是另一个事件,因为在我们发布密钥之前代码不会被触发。 但是如果我们在textarea中粘贴文本,这个代码也可以工作,因为事件也被触发了。

 document.getElementById("textArea").onkeyup = function() { var text = this.value.replace("\\n", ""); if (text.length > 15) { var chunks = text.match(/.{1,15}/g); if (chunks.length > 10) { chunks.splice(10, chunks.length - 1); alert("if text have more than 10 lines is removed"); } this.value = chunks.join("\\n"); } }; 
 <textarea rows="18" cols="50" id="textArea"> </textarea> 

在指定textarea字段的位置,需要将'enforceMaxLength'属性设置为true,然后将'maxLength'属性设置为字符数作为限制。 请查找以下extjs示例代码。 在示例中,我设置了不超过10个字符的限制。 希望这可以帮助。

Ext.create('Ext.form.Panel', {
title: 'Contact Info',
width: 300,
bodyPadding: 10,
renderTo: Ext.getBody(),
items: [{
    xtype: 'textarea',
    name: 'name',
    fieldLabel: 'Name',
    enforceMaxLength:true,
    maxLength:10,
    allowBlank: false  // requires a non-empty value
}]

});

对于10行接受条件

$(document).ready(function(){

    var lines = 10;
    var linesUsed = $('#linesUsed');

    $('#countMe').keydown(function(e) {

        newLines = $(this).val().split("\n").length;
        linesUsed.text(newLines);

        if(e.keyCode == 13 && newLines >= lines) {
            linesUsed.css('color', 'red');
            return false;
        }
        else {
            linesUsed.css('color', '');
        }
    });
});

我已经编写了解决方案,将cuted字符放在下一行的开头。 只允许10行,每行15个字符。

使用Ext JS解决方案

不幸的是,SO上的代码片段不适用于Ext JS。

因此,您可以在此codepen.io链接上看到它。

Ext.application(
{
    name: 'ExtApp',
    launch: function ()
    {
        Ext.create('Ext.form.Panel',
        {
            title: 'Sample TextArea',
            bodyPadding: 10,
            renderTo: Ext.getBody(),
            title: 'Restricted number of characters per line in textarea',
            height: 500,
            width: 700,
            items:
            [{
                xtype: 'textareafield',
                grow: true,
                fieldLabel: 'Please write your text:',
                height: 320,
                width: 480,
                listeners:
                {
                    change: function(self, newVal)
                    {
                        var chunks = newVal.split(/\r*\n/g),
                            lastLineCutedTxt = '';

                        for(var i = 0; i < chunks.length; i++)
                        {
                            chunks[i] = lastLineCutedTxt + chunks[i];

                            if(chunks[i].length > 15)
                            {
                                lastLineCutedTxt = chunks[i].slice(15);
                                chunks[i] = chunks[i].slice(0, 15);
                            }
                            else lastLineCutedTxt = '';
                        }

                        if(lastLineCutedTxt != '')
                            chunks.push(lastLineCutedTxt);

                        self.suspendEvent('change');
                        self.setValue(chunks.slice(0, 10).join('\n'));
                        self.resumeEvent('change');
                    }
                }
            }]
        });
    }
});
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/ext-all.js"></script>
<link rel="stylesheet" type="text/css" href="http://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-triton/resources/theme-triton-all.css">
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-triton/theme-triton.js"></script>

使用纯JavaScript解决方案

 var txtArea = document.getElementById('txt-area') txtArea.onkeyup = function(e) { var chunks = this.value.split(/\\r*\\n/g), lastLineCutedTxt = ''; for(var i = 0; i < chunks.length; i++) { chunks[i] = lastLineCutedTxt + chunks[i]; if(chunks[i].length > 15) { lastLineCutedTxt = chunks[i].slice(15); chunks[i] = chunks[i].slice(0, 15); } else lastLineCutedTxt = ''; } if(lastLineCutedTxt != '') chunks.push(lastLineCutedTxt); this.value = chunks.slice(0, 10).join('\\n'); }; 
 <textarea id="txt-area" rows="16" cols="35"></textarea> 

暂无
暂无

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

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