jQuery를 사용하여 텍스트 영역을 자동으로 확장하려면 어떻게해야합니까?
회의 의제를 설명하는 텍스트 상자가 있으므로 의제 텍스트가 해당 텍스트 상자 영역을 계속 확장 할 때 해당 텍스트 상자를 확장하고 싶습니다.
jQuery를 사용하여 텍스트 영역을 자동으로 확장하려면 어떻게해야합니까?
회의 의제를 설명하는 텍스트 상자가 있으므로 의제 텍스트가 해당 텍스트 상자 영역을 계속 확장 할 때 해당 텍스트 상자를 확장하고 싶습니다.
답변:
나는 많은 것을 시도했고
이것은 훌륭합니다. 연결이 끊어졌습니다. 최신 버전은 여기에서 볼 수 있습니다 . 이전 버전은 아래를 참조하십시오.
텍스트 영역에서 Enter 키를 길게 눌러보십시오. 다른 자동 확장 텍스트 영역 플러그인과 효과를 비교하십시오 ....
주석을 기준으로 편집
$(function() {
$('#txtMeetingAgenda').autogrow();
});
참고 : 필요한 js 파일을 포함시켜야합니다 ...
확장 / 수축시에 & 떨어져 점멸에서 텍스트 영역에서 스크롤을 방지하기 위해, 당신은을 설정할 수 있습니다 overflow에 hidden뿐만 아니라 :
$('#textMeetingAgenda').css('overflow', 'hidden').autogrow()
최신 정보:
위의 링크가 끊어졌습니다. 그러나 여전히 자바 스크립트 파일을 얻을 수 있습니다 .
플러그인을 원하지 않으면 매우 간단한 해결책이 있습니다.
$("textarea").keyup(function(e) {
while($(this).outerHeight() < this.scrollHeight + parseFloat($(this).css("borderTopWidth")) + parseFloat($(this).css("borderBottomWidth"))) {
$(this).height($(this).height()+1);
};
});
다른 텍스트 영역 질문에 대답하는 데 사용한 jsFiddle 에서 작동하는 것을 참조 하십시오 .
텍스트를 제거 할 때 반대로하거나 작게 만드는 질문에 대답하려면 jsFiddle
그리고 플러그인을 원한다면
if (this.clientHeight < this.scrollHeight) { this.style.height = this.scrollHeight + 'px'; }
텍스트 영역을 늘리거나 줄입니다. 이 데모는 jQuery를 사용하여 이벤트 바인딩을 수행하지만 반드시 필요한 것은 아닙니다.
( IE 지원 없음-IE는 행 속성 변경에 응답하지 않습니다 )
<textarea class='autoExpand' rows='3' data-min-rows='3' placeholder='Auto-Expanding Textarea'></textarea>
textarea{
display:block;
box-sizing: padding-box;
overflow:hidden;
padding:10px;
width:250px;
font-size:14px;
margin:50px auto;
border-radius:8px;
border:6px solid #556677;
}
$(document)
.one('focus.textarea', '.autoExpand', function(){
var savedValue = this.value;
this.value = '';
this.baseScrollHeight = this.scrollHeight;
this.value = savedValue;
})
.on('input.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;
});
당신은 이것을 시도 할 수 있습니다
$('#content').on('change keyup keydown paste cut', 'textarea', function () {
$(this).height(0).height(this.scrollHeight);
}).find('textarea').change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="content">
<textarea>How about it</textarea><br />
<textarea rows="5">111111
222222
333333
444444
555555
666666</textarea>
</div>
SpYk3HH 덕분에 그의 솔루션으로 시작하여이 솔루션으로 전환했습니다.이 솔루션은 축소 기능을 추가하고 훨씬 간단하고 빠릅니다.
$("textarea").keyup(function(e) {
$(this).height(30);
$(this).height(this.scrollHeight + parseFloat($(this).css("borderTopWidth")) + parseFloat($(this).css("borderBottomWidth")));
});
현재 Chrome, Firefox 및 Android 2.3.3 브라우저에서 테스트되었습니다.
일부 브라우저에서 스크롤 막대가 깜박일 수 있습니다. 이 CSS를 추가하여 문제를 해결하십시오.
textarea{ overflow:hidden; }
1px것이 좋을 것 같습니다)
자동 확장 가능 텍스트 영역을 정의하려면 다음 두 가지를 수행해야합니다.
다음은 작업을 수행 하는 수제 기능 입니다.
거의 모든 브라우저에서 잘 작동합니다 (<IE7) . 방법은 다음과 같습니다.
//Here is an event to get TextArea expand when you press Enter Key in it.
// intiate a keypress event
$('textarea').keypress(function (e) {
if(e.which == 13) {
var control = e.target;
var controlHeight = $(control).height();
//add some height to existing height of control, I chose 17 as my line-height was 17 for the control
$(control).height(controlHeight+17);
}
});
$('textarea').blur(function (e) {
var textLines = $(this).val().trim().split(/\r*\n/).length;
$(this).val($(this).val().trim()).height(textLines*17);
});
여기 에 대한 게시물이 있습니다.
좋은 결과를 얻기 전에 Textarea Expander jQuery 플러그인을 사용했습니다 .
누구나이 jQuery 플러그인 xautoresize-jquery를 시도해야합니다 . 정말 좋으며 문제를 해결해야합니다.
function autosize(textarea) {
$(textarea).height(1); // temporarily shrink textarea so that scrollHeight returns content height when content does not fill textarea
$(textarea).height($(textarea).prop("scrollHeight"));
}
$(document).ready(function () {
$(document).on("input", "textarea", function() {
autosize(this);
});
$("textarea").each(function () {
autosize(this);
});
});
( input이벤트를 사용하므로 Internet Explorer 9 이전 버전에서는 작동하지 않습니다. )
방금 페이지로드시 텍스트 영역을 확장하기 위해이 기능을 만들었습니다. 그냥 변경 each에 keyup와 텍스트 영역이에 입력 될 때 발생합니다.
// On page-load, auto-expand textareas to be tall enough to contain initial content
$('textarea').each(function(){
var pad = parseInt($(this).css('padding-top'));
if ($.browser.mozilla)
$(this).height(1);
var contentHeight = this.scrollHeight;
if (!$.browser.mozilla)
contentHeight -= pad * 2;
if (contentHeight > $(this).height())
$(this).height(contentHeight);
});
Chrome, IE9 및 Firefox에서 테스트되었습니다. 불행히도 Firefox에는 이에 대한 잘못된 값을 반환하는 이 버그 가 scrollHeight있으므로 위의 코드에는 해결 방법이 포함되어 있습니다.
Reigel이 제공 한 답변 (허용 된 답변)에서 몇 가지 버그가 수정되었습니다.
공백과 관련하여 몇 가지 남아있는 문제가 있습니다. 이중 공백에 대한 솔루션이 보이지 않고 그림자에서 단일 공백으로 표시됩니다 (html 렌더링). 공백이 없어야하기 때문에 & nbsp;를 사용하여 풀 수 없습니다. 또한 텍스트 영역은 공백 다음에 줄을 끊습니다. 해당 공간을위한 공간이 없으면 이전 지점에서 줄을 끊습니다. 제안은 환영합니다.
수정 된 코드 :
(function ($) {
$.fn.autogrow = function (options) {
var $this, minHeight, lineHeight, shadow, update;
this.filter('textarea').each(function () {
$this = $(this);
minHeight = $this.height();
lineHeight = $this.css('lineHeight');
$this.css('overflow','hidden');
shadow = $('<div></div>').css({
position: 'absolute',
'word-wrap': 'break-word',
top: -10000,
left: -10000,
width: $this.width(),
fontSize: $this.css('fontSize'),
fontFamily: $this.css('fontFamily'),
lineHeight: $this.css('lineHeight'),
resize: 'none'
}).appendTo(document.body);
update = function () {
shadow.css('width', $(this).width());
var val = this.value.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/\n/g, '<br/>')
.replace(/\s/g,' ');
if (val.indexOf('<br/>', val.length - 5) !== -1) { val += '#'; }
shadow.html(val);
$(this).css('height', Math.max(shadow.height(), minHeight));
};
$this.change(update).keyup(update).keydown(update);
update.apply(this);
});
return this;
};
}(jQuery));
축소 크기가 추가 된 SpYk3HH 코드.
function get_height(elt) {
return elt.scrollHeight + parseFloat($(elt).css("borderTopWidth")) + parseFloat($(elt).css("borderBottomWidth"));
}
$("textarea").keyup(function(e) {
var found = 0;
while (!found) {
$(this).height($(this).height() - 10);
while($(this).outerHeight() < get_height(this)) {
$(this).height($(this).height() + 1);
found = 1;
};
}
});
이것은 나를 위해 더 잘 작동했습니다.
$('.resiText').on('keyup input', function() {
$(this).css('height', 'auto').css('height', this.scrollHeight + (this.offsetHeight - this.clientHeight));
});
.resiText {
box-sizing: border-box;
resize: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea class="resiText"></textarea>
사람들은 과도하게 일한 솔루션을 가지고있는 것 같습니다 ...
이것이 내가하는 방법입니다.
$('textarea').keyup(function()
{
var
$this = $(this),
height = parseInt($this.css('line-height'), 10),
padTop = parseInt($this.css('padding-top'), 10),
padBot = parseInt($this.css('padding-bottom'), 10);
$this.height(0);
var
scroll = $this.prop('scrollHeight'),
lines = (scroll - padTop - padBot) / height;
$this.height(height * lines);
});
이것은 줄 바꿈뿐만 아니라 긴 줄에서도 작동합니다.
작동하는 것처럼 보이는이 jquery 함수를 작성했습니다.
CSS로 최소 높이를 지정해야하며 코딩을 원하지 않는 한 길이가 두 자리 여야합니다. 즉 12px;
$.fn.expand_ta = function() {
var val = $(this).val();
val = val.replace(/</g, "<");
val = val.replace(/>/g, ">");
val += "___";
var ta_class = $(this).attr("class");
var ta_width = $(this).width();
var min_height = $(this).css("min-height").substr(0, 2);
min_height = parseInt(min_height);
$("#pixel_height").remove();
$("body").append('<pre class="'+ta_class+'" id="pixel_height" style="position: absolute; white-space: pre-wrap; visibility: hidden; word-wrap: break-word; width: '+ta_width+'px; height: auto;"></pre>');
$("#pixel_height").html(val);
var height = $("#pixel_height").height();
if (val.substr(-6) == "<br />"){
height = height + min_height;
};
if (height >= min_height) $(this).css("height", height+"px");
else $(this).css("height", min_height+"px");
}
Reigel이 게시 한 플러그인을 사용하는 사람은 Internet Explorer에서 실행 취소 기능을 사용할 수 없게됩니다 (데모를 진행하십시오).
이것이 문제라면 @richsage가 게시 한 플러그인을 사용하는 것이 좋습니다 .이 문제가 발생하지 않기 때문입니다. 자세한 내용은 Ultimate Resizing Textarea 검색 의 두 번째 글 머리 기호 를 참조하십시오.
아주 멋진도있다 bgrins/ExpandingTextareas (github)하여 게시에 기반 프로젝트, 닐 젠킨스 라는 우아한 만들어진 텍스트 영역을 확장은
애니메이션과 자동 축소를 원했습니다. 사람들이 그것을 위해 매우 강렬한 솔루션을 생각해 냈기 때문에 조합은 분명히 어렵습니다. 다중 텍스트 영역으로도 만들었습니다. 그리고 jQuery 플러그인만큼 엄청나게 무겁지는 않습니다.
나는 VSYNC의 대답에 자신을 기반으로 한 (그리고 그가 그것을 위해 만든 개선), http://codepen.io/anon/pen/vlIwj은 내 개선 codepen된다.
HTML
<textarea class='autoExpand' rows='3' data-min-rows='3' placeholder='Auto-Expanding Textarea'></textarea>
CSS
body{ background:#728EB2; }
textarea{
display:block;
box-sizing: padding-box;
overflow:hidden;
padding:10px;
width:250px;
font-size:14px;
margin:50px auto;
border-radius:8px;
border:6px solid #556677;
transition:all 1s;
-webkit-transition:all 1s;
}
JS
var rowheight = 0;
$(document).on('input.textarea', '.autoExpand', function(){
var minRows = this.getAttribute('data-min-rows')|0,
rows = this.value.split("\n").length;
$this = $(this);
var rowz = rows < minRows ? minRows : rows;
var rowheight = $this.attr('data-rowheight');
if(!rowheight){
this.rows = rowz;
$this.attr('data-rowheight', (this.clientHeight - parseInt($this.css('padding-top')) - parseInt($this.css('padding-bottom')))/ rowz);
}else{
rowz++;
this.style.cssText = 'height:' + rowz * rowheight + 'px';
}
});
Knockout을 사용 하여이 작업을 수행하려고한다고 가정 해 봅시다 ... 방법은 다음과 같습니다.
페이지에서 :
<textarea data-bind="event: { keyup: $root.GrowTextArea }"></textarea>
뷰 모델에서 :
self.GrowTextArea = function (data, event) {
$('#' + event.target.id).height(0).height(event.target.scrollHeight);
}
이것은 내가하는 것처럼 녹아웃에 의해 여러 개의 텍스트 영역이 생성 된 경우에도 작동합니다.
간단한 해결책 :
HTML :
<textarea class='expand'></textarea>
JS :
$('textarea.expand').on('input', function() {
$(this).scrollTop($(this).height());
});
$('textarea.expand').scroll(function() {
var h = $(this).scrollTop();
if (h > 0)
$(this).height($(this).height() + h);
});
가장 간단한 해결책 :
html :
<textarea class="auto-expand"></textarea>
CSS :
.auto-expand {
overflow:hidden;
min-height: 80px;
}
js (jquery) :
$(document).ready(function () {
$("textarea.auto-expand").focus(function () {
var $minHeight = $(this).css('min-height');
$(this).on('input', function (e) {
$(this).css('height', $minHeight);
var $newHeight = $(this)[0].scrollHeight;
$(this).css('height', $newHeight);
});
});
});
순수 JS 솔루션
function autoSize() {
if (element) {
element.setAttribute('rows', 2) // minimum rows
const rowsRequired = parseInt(
(element.scrollHeight - TEXTAREA_CONFIG.PADDING) / TEXTAREA_CONFIG.LINE_HEIGHT
)
if (rowsRequired !== parseInt(element.getAttribute('rows'))) {
element.setAttribute('rows', rowsRequired)
}
}
}
function autoResizeTextarea() {
for (let index = 0; index < $('textarea').length; index++) {
let element = $('textarea')[index];
let offset = element.offsetHeight - element.clientHeight;
$(element).css('resize', 'none');
$(element).on('input', function() {
$(this).height(0).height(this.scrollHeight - offset - parseInt($(this).css('padding-top')));
});
}
}
https://codepen.io/nanachi1/pen/rNNKrzQ
이 작동합니다.
@Georgiy Ivankin은 의견에 제안을했지만 성공적으로 사용했습니다 :)-,하지만 약간 변경되었습니다.
$('#note').on('keyup',function(e){
var maxHeight = 200;
var f = document.getElementById('note');
if (f.clientHeight < f.scrollHeight && f.scrollHeight < maxHeight )
{ f.style.height = f.scrollHeight + 'px'; }
});
최대 200px 높이에 도달하면 확장이 중지됩니다.
오래된 질문이지만 다음과 같이 할 수 있습니다.
html :
<textarea class="text-area" rows="1"></textarea>
jquery :
var baseH; // base scroll height
$('body')
.one('focus.textarea', '.text-area', function(e) {
baseH = this.scrollHeight;
})
.on('input.textarea', '.text-area', function(e) {
if(baseH < this.scrollHeight) {
$(this).height(0).height(this.scrollHeight);
}
else {
$(this).height(0).height(baseH);
}
});
이 방법으로 자동 크기 조정은 "text-area"클래스가있는 모든 텍스트 영역에 적용됩니다. 텍스트가 제거되면 축소됩니다.
jsfiddle :
간단한 jQuery 솔루션 :
$("textarea").keyup(function() {
var scrollHeight = $(this).prop('scrollHeight') - parseInt($(this).css("paddingTop")) - parseInt($(this).css("paddingBottom"));
if (scrollHeight > $(this).height()) {
$(this).height(scrollHeight + "px");
}
});
HTML :
<textarea rows="2" style="padding: 20px; overflow: hidden; resize: none;"></textarea>
오버플로 는 숨겨져 야합니다. 마우스로 크기를 조정하지 않으려면 크기 조정 이 없습니다 .