【问题标题】:Textarea to allow user to enter only 2 lines [duplicate]Textarea允许用户仅输入2行[重复]
【发布时间】:2015-05-15 21:29:57
【问题描述】:

我需要一个文本区域,允许用户只输入 2 行文本。

当 lineCount 等于 2 时,我在 keyDown 事件上通过 e.preventDefault() 完成了此操作。问题是当用户使用退格键并删除输入的文本时。

如何跟踪行并允许再次输入,直到用户再次输入两行?

这是我能够完成的:

var lineCount = 0;
$('#editor').keydown(function (e) {
    if (e.keyCode == 13) {
        lineCount++;
    }
    if (e.keyCode == 8) {
       //needs to remove characters, deduct linecount when it gets to first line and reinstate typing
       return true;
    }
    if (lineCount >= 2) {
       e.preventDefault();
       return false;
    }
});

http://jsfiddle.net/blueberry20/yphkafqn/2/

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    在 jQuery (>1.6) 中可能是这样的:

    $(document).ready(function () {
    
        var lines = 2;
    
        $('#mytext').keydown(function (e) {
            newLines = $(this).val().split("\n").length;
    
            if (newLines > lines) {
                $("#mytext").prop('disabled', true);
            } else {
                $("#mytext").prop('disabled', false);
            }
        });
    
        $('#button').click(function () {
            $("#mytext").val('');
            $("#mytext").prop('disabled', false);
        });
    });
    

    http://jsfiddle.net/6vwLLu5h/1/

    它不适用于粘贴,如果用户不使用换行符。

    【讨论】:

    • 从可用性的角度来看,这很糟糕。如果用户尝试输入第三行,则所有内容都被锁定,无法进行进一步编辑。为什么任何人都想要那个?
    • @Stargazer712 是的 - 关于他的问题,我给出了一种可能的解决方案 - 挖掘更多他可以为其添加更多功能:一个按钮来重新启用 textarea? - 在现实世界中,有人可能想要那个。 :)
    猜你喜欢
    • 2023-03-12
    • 1970-01-01
    • 2013-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-29
    相关资源
    最近更新 更多