我有两个textarea
元素需要调整为其中的人物类型(在Y轴中)。我编写的代码成功调整了textarea
的大小,但该代码不适用于页面上的许多textareas
。
工作代码的代码 - 一个textarea
现在,如果您运行此代码,它将完全正常,当您键入或转到新行时,该框将响应该行。它会被拉长。
有人可以解释为什么这个代码不起作用(甚至更好,告诉我我需要做些什么来使它工作)两个或更多textareas?对于这样的事情:
$(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>
答案 0 :(得分:2)
将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;
});
答案 1 :(得分:1)
我修改了您要使用的代码并跟踪该框是否已使用数据属性进行初始化。如果焦点代码尚未初始化并且数据属性设置
,它将仅处理焦点代码$(document)
.on('focus.autoExpand', 'textarea.autoExpand', function(){
if(!$(this).data('initialized')){
var savedValue = this.value;
this.value = '';
this.baseScrollHeight = this.scrollHeight;
this.value = savedValue;
$(this).data('initialized', true);
}
})
.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;
});