gpt4 book ai didi

javascript - 许多文本区域无法正常工作 - JQuery

转载 作者:行者123 更新时间:2023-11-30 11:18:34 25 4
gpt4 key购买 nike

我有两个 textarea 元素需要根据其中的人物类型调整大小(在 Y 轴上)。我已经编写了成功调整 textarea 大小的代码,但该代码不适用于页面上的许多 textareas

工作代码的代码 - 一个文本区域

现在,如果您运行此代码,它会工作得很好,当您键入或转到新行时,该框将对此做出响应。它将被拉伸(stretch)。

有人可以解释为什么这段代码对两个或更多文本区域不起作用(更好的是,告诉我我需要做什么才能让它起作用)?对于这样的事情:

 $(document)
.one('focus.autoExpand', 'textarea.autoExpand', function(){
var savedValue = this.value;
this.value = '';
this.baseScrollHeight = this.scrollHeight;
this.value = savedValue;
})
.on('input.autoExpand', 'textarea.autoExpand', function(){
var minRows = this.getAttribute('data-min-rows')|0, rows;
this.rows = minRows;
rows = Math.ceil((this.scrollHeight - this.baseScrollHeight) / 16);
this.rows = minRows + rows;
});
    /* JUST FOR THIS DEMO */
html, body {
height: 100%;
}

body {
background: #4A90E2;
display: flex;
align-items: center;
}

textarea {
display: block;
box-sizing: padding-box;
overflow: hidden;
padding: 10px;
width: 250px;
font-size: 14px;
margin: 50px auto;
border-radius: 6px;
box-shadow: 2px 2px 8px rgba(0, 0, 0, 0.3);
border: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea class='autoExpand' rows='3'
data-min-rows='3' placeholder='Auto-Expanding Textarea'></textarea>
<textarea class='autoExpand' rows='3'
data-min-rows='3' placeholder='Auto-Expanding Textarea'></textarea>

最佳答案

one 更改为 on,但是添加了逻辑以使其知道不要多次重新初始化同一元素。

$(document)
.on('focus.autoExpand', 'textarea.autoExpand', function() {
if (!this.getAttribute('data-initialized')){
this.setAttribute('data-initialized', 'true');
var savedValue = this.value;
this.value = '';
this.baseScrollHeight = this.scrollHeight;
this.value = savedValue;
}
})
.on('input.autoExpand', 'textarea.autoExpand', function() {
var minRows = this.getAttribute('data-min-rows') | 0,
rows;
this.rows = minRows;
rows = Math.ceil((this.scrollHeight - this.baseScrollHeight) / 16);
this.rows = minRows + rows;
});

关于javascript - 许多文本区域无法正常工作 - JQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50632222/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com