如何检测我是否已删除文本区域内的多行

时间:2018-08-28 04:54:45

标签: javascript jquery html css

我有一个自动增长的TextArea。按下Enter键后,高度正在调整。如果要删除textarea的多行中的一行,我想减小高度。这是我当前的代码:

$('.autogrow').each(function () {
    h(this);
}).on('keypress', function (e) {
    if(e.which == 13){
        h(this);
    }
});

function h(e) {
    $(e).css({'height':'auto','overflow-y':'hidden'}).height(e.scrollHeight);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea name="invite_email" id="invite_email" value="" class="autogrow" placeholder="Email Address" style="resize:none;overflow:hidden;-ms-overflow-style: none;min-height: 44px;border: 1px solid #e3e3e3;height: 44px; background: #fff;border-radius: 4px;    padding: 6px 12px !important;font-size: 14px !important; line-height: 2; width: 100%; margin: 0;"></textarea>

2 个答案:

答案 0 :(得分:2)

您正在调用仅在按Enter键时调整大小的函数。

// Model
public class PersonViewModel
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

// Controller action
public async Task<ActionResult> Index(PersonViewModel model)
{
    var data = new PersonModel();
    data.FirstName = model.FirstName;
    data.LastName = model.LastName;

    // save changes with await

    return View();
}

删除该内容,并在每次按键时调用该函数以调整大小

if(e.which == 13){
    h(this);
}
$('.autogrow').each(function () {
    h(this);
}).on('keyup', function (e) {
    h(this);
  
});

function h(e) {
    $(e).css({'height':'auto','overflow-y':'hidden'}).height(e.scrollHeight)
}

答案 1 :(得分:2)

尝试播放行数:

var ROW_HEIGHT = 13;

function resize_(e) {
  var rows = txt.value.split(/\n/).length;
  txt.style.height = rows * ROW_HEIGHT + 'px';
}

var txt = document.getElementById('txt');
txt.addEventListener('paste', resize_);
txt.addEventListener('input', resize_);
txt.addEventListener('change', resize_);
<textarea id="txt">row 1
row 2</textarea>