프로토 타입을 사용하여 텍스트 영역을 자동 크기 조정하는 방법은 무엇입니까?
현재 근무중인 회사의 내부 판매 응용 프로그램을 만들고 있는데 사용자가 배달 주소를 변경할 수있는 양식이 있습니다.
이제 기본 주소 세부 정보에 사용하는 텍스트 영역이 텍스트 영역을 차지하고 텍스트가 변경되면 자동으로 크기가 조정되면 훨씬 멋지게 보일 것이라고 생각합니다.
여기 현재 스크린 샷이 있습니다.
어떤 아이디어?
@ 크리스
좋은 지적이지만 크기를 조정하려는 이유가 있습니다. 나는 그것이 포함 된 정보의 영역이되는 영역을 원한다. 스크린 샷에서 볼 수 있듯이 고정 텍스트 영역이 있으면 세로 공간이 상당히 많이 차지합니다.
글꼴을 줄일 수는 있지만 크고 읽기 쉬운 주소가 필요합니다. 이제 텍스트 영역의 크기를 줄일 수는 있지만 주소 줄이 3 또는 4 (1은 5) 인 사람들에게는 문제가 있습니다. 사용자가 스크롤바를 사용하도록하는 것은 중요합니다.
좀 더 구체적이어야한다고 생각합니다. 세로 크기 조정 후 너비가 중요하지 않습니다. 이 문제가 발생하는 유일한 문제는 창 너비가 너무 작을 때 ISO 숫자 (큰 "1")가 주소 아래로 밀리는 것입니다 (스크린 샷에서 볼 수 있듯이).
그것은 직무를 갖는 것이 아닙니다. 불필요한 공간을 차지하지 않지만 사용자가 편집 할 수있는 텍스트 필드를 갖는 것이지만 그 안에 모든 텍스트가 표시됩니다.
누군가가 문제에 접근하는 다른 방법을 생각해 내면 나는 그것에 대해서도 개방적입니다.
코드가 약간 이상하게 작동했기 때문에 코드를 약간 수정했습니다. 방금 입력 한 문자를 고려하지 않기 때문에 키 업시 활성화되도록 변경했습니다.
resizeIt = function() {
var str = $('iso_address').value;
var cols = $('iso_address').cols;
var linecount = 0;
$A(str.split("\n")).each(function(l) {
linecount += 1 + Math.floor(l.length / cols); // Take into account long lines
})
$('iso_address').rows = linecount;
};
Facebook은 사람들의 벽에 글을 쓰지만 세로 방향으로 만 크기를 조정할 때 사용합니다.
가로 크기 조정은 단어 줄 바꿈, 긴 줄 등으로 인해 혼란스러워하지만 세로 크기 조정은 꽤 안전하고 좋은 것 같습니다.
내가 아는 Facebook 사용 초보자는 아무도 그것에 대해 언급하거나 혼동하지 않았습니다. 나는 이것을 '계속해서 구현하라'고 말하는 일화적인 증거로 사용합니다.
프로토 타입을 사용하여 JavaScript 코드를 작성하는 방법 (내가 익숙하기 때문에) :
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="http://www.google.com/jsapi"></script>
<script language="javascript">
google.load('prototype', '1.6.0.2');
</script>
</head>
<body>
<textarea id="text-area" rows="1" cols="50"></textarea>
<script type="text/javascript" language="javascript">
resizeIt = function() {
var str = $('text-area').value;
var cols = $('text-area').cols;
var linecount = 0;
$A(str.split("\n")).each( function(l) {
linecount += Math.ceil( l.length / cols ); // Take into account long lines
})
$('text-area').rows = linecount + 1;
};
// You could attach to keyUp, etc. if keydown doesn't work
Event.observe('text-area', 'keydown', resizeIt );
resizeIt(); //Initial on load
</script>
</body>
</html>
추신 : 분명히이 JavaScript 코드는 매우 순진하고 잘 테스트되지 않았으며 소설이있는 텍스트 상자에서 사용하고 싶지는 않지만 일반적인 아이디어를 얻습니다.
이러한 답변 중 일부를 개선 한 것은 CSS가 더 많은 작업을 수행하도록하는 것입니다.
기본 경로는 다음과 같습니다.
- 를
textarea
숨길 컨테이너 요소를 만듭니다.div
- 자바 스크립트를 사용하여
textarea
의 콘텐츠를div
의 - 브라우저가 해당 div의 높이를 계산하는 작업을 수행하게하십시오.
- 브라우저는 숨겨진 렌더링 / 크기 조정을 처리하므로
div
명시 적으로textarea
높이를 설정하지 마십시오 .
document.addEventListener('DOMContentLoaded', () => {
textArea.addEventListener('change', autosize, false)
textArea.addEventListener('keydown', autosize, false)
textArea.addEventListener('keyup', autosize, false)
autosize()
}, false)
function autosize() {
// Copy textarea contents to div browser will calculate correct height
// of copy, which will make overall container taller, which will make
// textarea taller.
textCopy.innerHTML = textArea.value.replace(/\n/g, '<br/>')
}
html, body, textarea {
font-family: sans-serif;
font-size: 14px;
}
.textarea-container {
position: relative;
}
.textarea-container > div, .textarea-container > textarea {
word-wrap: break-word; /* make sure the div and the textarea wrap words in the same way */
box-sizing: border-box;
padding: 2px;
width: 100%;
}
.textarea-container > textarea {
overflow: hidden;
position: absolute;
height: 100%;
}
.textarea-container > div {
padding-bottom: 1.5em; /* A bit more than one additional line of text. */
visibility: hidden;
}
<div class="textarea-container">
<textarea id="textArea"></textarea>
<div id="textCopy"></div>
</div>
텍스트 영역을 자동 크기 조정하는 또 다른 기술이 있습니다.
- 줄 높이 대신 픽셀 높이를 사용합니다. 비례 글꼴을 사용하는 경우 줄 바꿈을보다 정확하게 처리합니다.
- ID 또는 요소를 입력으로 승인
- 선택적인 최대 높이 매개 변수를 허용합니다. 텍스트 영역이 특정 크기 이상으로 커지지 않도록하려는 경우에 유용합니다 (화면 전체를 유지하고 레이아웃 중단 방지 등).
- Firefox 3 및 Internet Explorer 6 에서 테스트
코드 : (일반 바닐라 JavaScript)
function FitToContent(id, maxHeight)
{
var text = id && id.style ? id : document.getElementById(id);
if (!text)
return;
/* Accounts for rows being deleted, pixel value may need adjusting */
if (text.clientHeight == text.scrollHeight) {
text.style.height = "30px";
}
var adjustedHeight = text.clientHeight;
if (!maxHeight || maxHeight > adjustedHeight)
{
adjustedHeight = Math.max(text.scrollHeight, adjustedHeight);
if (maxHeight)
adjustedHeight = Math.min(maxHeight, adjustedHeight);
if (adjustedHeight > text.clientHeight)
text.style.height = adjustedHeight + "px";
}
}
데모 : (jQuery 사용, 지금 입력하고있는 텍스트 영역의 대상 -Firebug가 설치된 경우 두 샘플을 콘솔에 붙여 넣고이 페이지에서 테스트하십시오)
$("#post-text").keyup(function()
{
FitToContent(this, document.documentElement.clientHeight)
});
아마도 가장 짧은 해결책 :
jQuery(document).ready(function(){
jQuery("#textArea").on("keydown keyup", function(){
this.style.height = "1px";
this.style.height = (this.scrollHeight) + "px";
});
});
이렇게하면 숨겨진 div 또는 이와 유사한 것이 필요하지 않습니다.
참고 : this.style.height = (this.scrollHeight) + "px";
텍스트 영역의 스타일 (선 높이, 패딩 및 그 종류)에 따라 놀아야 할 수도 있습니다 .
다음 은 텍스트 영역의 열 수에 의존하지 않는 텍스트 영역의 크기를 조정 하는 프로토 타입 버전입니다. 이 기능은 CSS를 통해 텍스트 영역을 제어 할 수있을뿐만 아니라 가변 너비 텍스트 영역을 가질 수 있기 때문에 탁월한 기술입니다. 또한이 버전은 남은 문자 수를 표시합니다. 요청하지는 않았지만 매우 유용한 기능이며 원치 않는 경우 쉽게 제거됩니다.
//inspired by: http://github.com/jaz303/jquery-grab-bag/blob/63d7e445b09698272b2923cb081878fd145b5e3d/javascripts/jquery.autogrow-textarea.js
if (window.Widget == undefined) window.Widget = {};
Widget.Textarea = Class.create({
initialize: function(textarea, options)
{
this.textarea = $(textarea);
this.options = $H({
'min_height' : 30,
'max_length' : 400
}).update(options);
this.textarea.observe('keyup', this.refresh.bind(this));
this._shadow = new Element('div').setStyle({
lineHeight : this.textarea.getStyle('lineHeight'),
fontSize : this.textarea.getStyle('fontSize'),
fontFamily : this.textarea.getStyle('fontFamily'),
position : 'absolute',
top: '-10000px',
left: '-10000px',
width: this.textarea.getWidth() + 'px'
});
this.textarea.insert({ after: this._shadow });
this._remainingCharacters = new Element('p').addClassName('remainingCharacters');
this.textarea.insert({after: this._remainingCharacters});
this.refresh();
},
refresh: function()
{
this._shadow.update($F(this.textarea).replace(/\n/g, '<br/>'));
this.textarea.setStyle({
height: Math.max(parseInt(this._shadow.getHeight()) + parseInt(this.textarea.getStyle('lineHeight').replace('px', '')), this.options.get('min_height')) + 'px'
});
var remaining = this.options.get('max_length') - $F(this.textarea).length;
this._remainingCharacters.update(Math.abs(remaining) + ' characters ' + (remaining > 0 ? 'remaining' : 'over the limit'));
}
});
를 호출하여 위젯을 작성하십시오 new Widget.Textarea('element_id')
. 기본 옵션은 객체로 전달하여 재정의 할 수 있습니다 (예 :) new Widget.Textarea('element_id', { max_length: 600, min_height: 50})
. 페이지의 모든 텍스트 영역에 대해 작성하려면 다음과 같이하십시오.
Event.observe(window, 'load', function() {
$$('textarea').each(function(textarea) {
new Widget.Textarea(textarea);
});
});
다음과 같은 해결책이 있습니다 JQuery
.
$(document).ready(function() {
var $abc = $("#abc");
$abc.css("height", $abc.attr("scrollHeight"));
})
abc
입니다 teaxtarea
.
아래 링크를 확인하십시오 : http://james.padolsey.com/javascript/jquery-plugin-autoresize/
$(document).ready(function () {
$('.ExpandableTextCSS').autoResize({
// On resize:
onResize: function () {
$(this).css({ opacity: 0.8 });
},
// After resize:
animateCallback: function () {
$(this).css({ opacity: 1 });
},
// Quite slow animation:
animateDuration: 300,
// More extra space:
extraSpace:20,
//Textarea height limit
limit:10
});
});
이것을 다시 방문하여 조금 더 깔끔하게 만들었습니다 ( Prototype / JavaScript 에 병이 많은 사람이 개선을 제안 할 수 는 있지만 ).
var TextAreaResize = Class.create();
TextAreaResize.prototype = {
initialize: function(element, options) {
element = $(element);
this.element = element;
this.options = Object.extend(
{},
options || {});
Event.observe(this.element, 'keyup',
this.onKeyUp.bindAsEventListener(this));
this.onKeyUp();
},
onKeyUp: function() {
// We need this variable because "this" changes in the scope of the
// function below.
var cols = this.element.cols;
var linecount = 0;
$A(this.element.value.split("\n")).each(function(l) {
// We take long lines into account via the cols divide.
linecount += 1 + Math.floor(l.length / cols);
})
this.element.rows = linecount;
}
}
그냥 다음과 같이 전화하십시오.
new TextAreaResize('textarea_id_name_here');
나는 아주 쉬운 것을 만들었습니다. 먼저 TextArea를 DIV에 넣었습니다. 둘째, ready
이 스크립트에 함수를 호출했습니다 .
<div id="divTable">
<textarea ID="txt" Rows="1" TextMode="MultiLine" />
</div>
$(document).ready(function () {
var heightTextArea = $('#txt').height();
var divTable = document.getElementById('divTable');
$('#txt').attr('rows', parseInt(parseInt(divTable .style.height) / parseInt(altoFila)));
});
단순한. 렌더링 된 div의 최대 높이를 한 행의 한 TextArea의 높이로 나눈 값입니다.
나는이 기능을 스스로 필요로했지만 여기에서 필요한 기능은 없습니다.
그래서 Orion의 코드를 사용하고 변경했습니다.
나는 최소 높이를 추가하여 파괴시 너무 작아지지 않도록했습니다.
function resizeIt( id, maxHeight, minHeight ) {
var text = id && id.style ? id : document.getElementById(id);
var str = text.value;
var cols = text.cols;
var linecount = 0;
var arStr = str.split( "\n" );
$(arStr).each(function(s) {
linecount = linecount + 1 + Math.floor(arStr[s].length / cols); // take into account long lines
});
linecount++;
linecount = Math.max(minHeight, linecount);
linecount = Math.min(maxHeight, linecount);
text.rows = linecount;
};
@memical의 답변과 같습니다.
그러나 나는 약간의 개선점을 발견했다. jQuery height()
함수를 사용할 수 있습니다 . 그러나 패딩 상단 및 패딩 하단 픽셀에 유의하십시오. 그렇지 않으면 텍스트 영역이 너무 빨리 커집니다.
$(document).ready(function() {
$textarea = $("#my-textarea");
// There is some diff between scrollheight and height:
// padding-top and padding-bottom
var diff = $textarea.prop("scrollHeight") - $textarea.height();
$textarea.live("keyup", function() {
var height = $textarea.prop("scrollHeight") - diff;
$textarea.height(height);
});
});
jQuery를 사용하지 않는 내 솔루션은 (때로는 같지 않아도되기 때문에) 아래에 있습니다. Internet Explorer 7 에서만 테스트되었지만 커뮤니티는 이것이 잘못된 이유를 모두 지적 할 수 있습니다.
textarea.onkeyup = function () { this.style.height = this.scrollHeight + 'px'; }
지금까지 나는 그것이 작동하는 방식을 정말로 좋아하고 다른 브라우저는 신경 쓰지 않으므로 모든 텍스트 영역에 적용 할 것입니다.
// Make all textareas auto-resize vertically
var textareas = document.getElementsByTagName('textarea');
for (i = 0; i<textareas.length; i++)
{
// Retain textarea's starting height as its minimum height
textareas[i].minHeight = textareas[i].offsetHeight;
textareas[i].onkeyup = function () {
this.style.height = Math.max(this.scrollHeight, this.minHeight) + 'px';
}
textareas[i].onkeyup(); // Trigger once to set initial height
}
다음은 Jeremy가 6 월 4 일에 게시 한 프로토 타입 위젯의 확장입니다.
텍스트 영역에서 제한을 사용하는 경우 사용자가 더 많은 문자를 입력하지 못하게합니다. 문자가 남아 있는지 확인합니다. 사용자가 텍스트를 텍스트 영역에 복사하면 텍스트가 최대 값에서 잘립니다. 길이:
/**
* Prototype Widget: Textarea
* Automatically resizes a textarea and displays the number of remaining chars
*
* From: http://stackoverflow.com/questions/7477/autosizing-textarea
* Inspired by: http://github.com/jaz303/jquery-grab-bag/blob/63d7e445b09698272b2923cb081878fd145b5e3d/javascripts/jquery.autogrow-textarea.js
*/
if (window.Widget == undefined) window.Widget = {};
Widget.Textarea = Class.create({
initialize: function(textarea, options){
this.textarea = $(textarea);
this.options = $H({
'min_height' : 30,
'max_length' : 400
}).update(options);
this.textarea.observe('keyup', this.refresh.bind(this));
this._shadow = new Element('div').setStyle({
lineHeight : this.textarea.getStyle('lineHeight'),
fontSize : this.textarea.getStyle('fontSize'),
fontFamily : this.textarea.getStyle('fontFamily'),
position : 'absolute',
top: '-10000px',
left: '-10000px',
width: this.textarea.getWidth() + 'px'
});
this.textarea.insert({ after: this._shadow });
this._remainingCharacters = new Element('p').addClassName('remainingCharacters');
this.textarea.insert({after: this._remainingCharacters});
this.refresh();
},
refresh: function(){
this._shadow.update($F(this.textarea).replace(/\n/g, '<br/>'));
this.textarea.setStyle({
height: Math.max(parseInt(this._shadow.getHeight()) + parseInt(this.textarea.getStyle('lineHeight').replace('px', '')), this.options.get('min_height')) + 'px'
});
// Keep the text/character count inside the limits:
if($F(this.textarea).length > this.options.get('max_length')){
text = $F(this.textarea).substring(0, this.options.get('max_length'));
this.textarea.value = text;
return false;
}
var remaining = this.options.get('max_length') - $F(this.textarea).length;
this._remainingCharacters.update(Math.abs(remaining) + ' characters remaining'));
}
});
@memical had an awesome solution for setting the height of the textarea on pageload with jQuery, but for my application I wanted to be able to increase the height of the textarea as the user added more content. I built off memical's solution with the following:
$(document).ready(function() {
var $textarea = $("p.body textarea");
$textarea.css("height", ($textarea.attr("scrollHeight") + 20));
$textarea.keyup(function(){
var current_height = $textarea.css("height").replace("px", "")*1;
if (current_height + 5 <= $textarea.attr("scrollHeight")) {
$textarea.css("height", ($textarea.attr("scrollHeight") + 20));
}
});
});
It's not very smooth but it's also not a client-facing application, so smoothness doesn't really matter. (Had this been client-facing, I probably would have just used an auto-resize jQuery plugin.)
For those that are coding for IE and encounter this problem. IE has a little trick that makes it 100% CSS.
<TEXTAREA style="overflow: visible;" cols="100" ....></TEXTAREA>
You can even provide a value for rows="n" which IE will ignore, but other browsers will use. I really hate coding that implements IE hacks, but this one is very helpful. It is possible that it only works in Quirks mode.
Internet Explorer, Safari, Chrome and Opera users need to remember to explicidly set the line-height value in CSS. I do a stylesheet that sets the initial properites for all text boxes as follows.
<style>
TEXTAREA { line-height: 14px; font-size: 12px; font-family: arial }
</style>
Here is a function I just wrote in jQuery to do it - you can port it to Prototype, but they don't support the "liveness" of jQuery so elements added by Ajax requests will not respond.
This version not only expands, but it also contracts when delete or backspace is pressed.
This version relies on jQuery 1.4.2.
Enjoy ;)
Usage:
$("#sometextarea").textareacontrol();
or (any jQuery selector for example)
$("textarea").textareacontrol();
It was tested on Internet Explorer 7/Internet Explorer 8, Firefox 3.5, and Chrome. All works fine.
Using ASP.NET, just simply do this:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Automatic Resize TextBox</title>
<script type="text/javascript">
function setHeight(txtarea) {
txtarea.style.height = txtdesc.scrollHeight + "px";
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:TextBox ID="txtarea" runat= "server" TextMode="MultiLine" onkeyup="setHeight(this);" onkeydown="setHeight(this);" />
</form>
</body>
</html>
참고 URL : https://stackoverflow.com/questions/7477/how-to-autosize-a-textarea-using-prototype
'development' 카테고리의 다른 글
스프링 MVC @ PathVariable (0) | 2020.07.22 |
---|---|
Intellij IDEA에서 접힌 패키지 체인을 확장하는 방법은 무엇입니까? (0) | 2020.07.22 |
이미지가 언제로드되는지 알기 위해 JavaScript 콜백을 만드는 방법은 무엇입니까? (0) | 2020.07.22 |
MSDeploy.exe를 통해 WMSvc에서 404 얻기 (0) | 2020.07.21 |
iOS 7에서 UIPickerView의 텍스트 색상을 어떻게 변경합니까? (0) | 2020.07.21 |