programing

크기 자동 조정을 사용하여 텍스트 영역 작성

yoursource 2022. 12. 11. 10:41
반응형

크기 자동 조정을 사용하여 텍스트 영역 작성

이것에는 또 다른 실마리가 있습니다.제가 시도해 본 것입니다.하지만 한 가지 문제가 있습니다.textarea내용을 삭제해도 축소되지 않습니다.clientHeight은 값 value value value value of of of of of of of of 의 .textarea

이 페이지의 코드는 다음과 같습니다.

function FitToContent(id, maxHeight)
{
   var text = id && id.style ? id : document.getElementById(id);
   if ( !text )
      return;

   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";
   }
}

window.onload = function() {
    document.getElementById("ta").onkeyup = function() {
      FitToContent( this, 500 )
    };
}

완전하면서도 심플한 솔루션

2022-08-30 업데이트(기본적으로 단일다중 텍스트 상자 지원 추가)

다음 코드가 작동합니다.

  • 키 입력 시.
  • 붙여넣기 텍스트(우클릭+ctrl+v)
  • 자르기 텍스트(우클릭+ctrl+x)를 사용합니다.
  • 텍스트가 프리 로드되어 있습니다.
  • 모든 텍스트 영역(복수텍스트 상자) 사이트 폭.
  • Firefox(v31-67 테스트 완료).
  • Chrome 탑재(v37-74 테스트 완료).
  • IE (v9-v11 테스트 완료)
  • 엣지 포함(v14-v18 테스트 완료).
  • IOS Safari 사용
  • Android Browser 탑재.
  • JavaScript strict 모드 사용.
  • w3c가 검증되었습니다.
  • 합리적이고 효율적입니다.

옵션 1(jQuery 포함)

이 옵션에는 jQuery가 필요하며 테스트 완료 후 1.7.2 - 3.6에서 동작하고 있습니다.

간단하죠. (마스터 스크립트파일에 이 jquery 코드를 추가하고 잊어버립니다).

$("textarea").each(function () {
  this.setAttribute("style", "height:" + (this.scrollHeight) + "px;overflow-y:hidden;");
}).on("input", function () {
  this.style.height = 0;
  this.style.height = (this.scrollHeight) + "px";
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea placeholder="Type, paste, cut text here...">PRELOADED TEXT.
This javascript should now add better support for IOS browsers and Android browsers.</textarea>
<textarea placeholder="Type, paste, cut text here..."></textarea>

Test on jsfiddle


OPTION 2 (Pure JavaScript)

간단하죠. (이 JavaScript를 마스터 스크립트 파일에 추가하고 잊어버립니다.)

const tx = document.getElementsByTagName("textarea");
for (let i = 0; i < tx.length; i++) {
  tx[i].setAttribute("style", "height:" + (tx[i].scrollHeight) + "px;overflow-y:hidden;");
  tx[i].addEventListener("input", OnInput, false);
}

function OnInput() {
  this.style.height = 0;
  this.style.height = (this.scrollHeight) + "px";
}
<textarea placeholder="Type, paste, cut text here...">PRELOADED TEXT. This JavaScript should now add better support for IOS browsers and Android browsers.</textarea>
<textarea placeholder="Type, paste, cut text here..."></textarea>

Test on jsfiddle


OPTION 3(jQuery 확장)

자동 크기를 조정할 텍스트 영역에 추가 체인을 적용하려는 경우 유용합니다.

jQuery.fn.extend({
  autoHeight: function () {
    function autoHeight_(element) {
      return jQuery(element)
        .css({ "height": 0, "overflow-y": "hidden" })
        .height(element.scrollHeight);
    }
    return this.each(function() {
      autoHeight_(this).on("input", function() {
        autoHeight_(this);
      });
    });
  }
});

로로 invoke invoke invoke로 $("textarea").autoHeight()


Javascript를 통한 텍스트 영역 업데이트

JavaScript를 통해 텍스트 영역에 콘텐츠를 삽입할 때 옵션 1의 함수를 호출하기 위해 다음 코드를 추가합니다.

$("textarea").trigger("input");

프리셋 텍스트 영역 높이

텍스트 영역의 초기 높이를 수정하려면 다음 조건을 추가해야 합니다.

const txHeight = 16;
const tx = document.getElementsByTagName("textarea");

for (let i = 0; i < tx.length; i++) {
  if (tx[i].value == '') {
    tx[i].setAttribute("style", "height:" + txHeight + "px;overflow-y:hidden;");
  } else {
    tx[i].setAttribute("style", "height:" + (tx[i].scrollHeight) + "px;overflow-y:hidden;");
  }
  tx[i].addEventListener("input", OnInput, false);
}

function OnInput(e) {
  this.style.height = 0;
  this.style.height = (this.scrollHeight) + "px";
}
<textarea placeholder="Type, paste, cut text here...">PRELOADED TEXT. This JavaScript should now add better support for IOS browsers and Android browsers.</textarea>
<textarea placeholder="Type, paste, cut text here..."></textarea>

이 방법은 다음과 같습니다(Firefox 3.6/4.0 및 Chrome 10/11).

var observe;
if (window.attachEvent) {
    observe = function (element, event, handler) {
        element.attachEvent('on'+event, handler);
    };
}
else {
    observe = function (element, event, handler) {
        element.addEventListener(event, handler, false);
    };
}
function init () {
    var text = document.getElementById('text');
    function resize () {
        text.style.height = 'auto';
        text.style.height = text.scrollHeight+'px';
    }
    /* 0-timeout to get the already changed text */
    function delayedResize () {
        window.setTimeout(resize, 0);
    }
    observe(text, 'change',  resize);
    observe(text, 'cut',     delayedResize);
    observe(text, 'paste',   delayedResize);
    observe(text, 'drop',    delayedResize);
    observe(text, 'keydown', delayedResize);

    text.focus();
    text.select();
    resize();
}
textarea {
    border: 0 none white;
    overflow: hidden;
    padding: 0;
    outline: none;
    background-color: #D0D0D0;
}
<body onload="init();">
<textarea rows="1" style="height:1em;" id="text"></textarea>
</body>

jsfiddle에서 시험해보고 싶다면 그것은 한 줄에서 시작해서 필요한 양만큼만 커집니다.싱글이라도 좋다textarea는 그런 것들이 것 싶었어요.textareas( 「 「 」 「 」 )이는, 으로 느립니다이 경우 정말 느립니다.(Firefox ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★」그래서 저는 순수한 CSS를 사용하는 접근방식을 정말 원합니다.이것은, 다음과 같은 방법으로 가능합니다.contenteditable, 전용으로 해

jQuery 솔루션은 요건에 맞게 css를 조정합니다.

css...

div#container textarea {
    min-width: 270px;
    width: 270px;
    height: 22px;
    line-height: 24px;
    min-height: 22px;
    overflow-y: hidden; /* fixes scrollbar flash - kudos to @brettjonesdev */
    padding-top: 1.1em; /* fixes text jump on Enter keypress */
}

javascript...

// auto adjust the height of
$('#container').delegate( 'textarea', 'keydown', function (){
    $(this).height( 0 );
    $(this).height( this.scrollHeight );
});
$('#container').find( 'textarea' ).keydown();

또는 jQuery 1.7+에 대한 대체 방법...

// auto adjust the height of
$('#container').on( 'keyup', 'textarea', function (){
    $(this).height( 0 );
    $(this).height( this.scrollHeight );
});
$('#container').find( 'textarea' ).keyup();

실험의 출발점으로 최소한의 스타일링으로 바이올린을 만들었습니다...http://jsfiddle.net/53eAy/951/

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Textarea autoresize</title>
    <style>
    textarea {
        overflow: hidden;
    }
    </style>
    <script>
    function resizeTextarea(ev) {
        this.style.height = '24px';
        this.style.height = this.scrollHeight + 12 + 'px';
    }

    var te = document.querySelector('textarea');
    te.addEventListener('input', resizeTextarea);
    </script>
</head>
<body>
    <textarea></textarea>
</body>
</html>

Firefox 14 및 Cromium 18에서 테스트 완료.숫자 24와 12는 임의입니다. 어떤 숫자가 가장 적합한지 테스트해 보십시오.

스타일이나 스크립트 태그가 없어도 괜찮지만, 조금 지저분한 imho가 됩니다(이것은 오래된 스타일의 HTML+J이므로 권장하지 않습니다).

<textarea style="overflow: hidden" onkeyup="this.style.height='24px'; this.style.height = this.scrollHeight + 12 + 'px';"></textarea>

편 : 코코코현 。onkeyup Atribut 、 addEventListener on on on on on 。
: 키 이 키
: 사용 전 기능 선언: 사용 전 기능 선언.
@MA-Maddin : @MA-Maddin (thnx @WASD42 @MA-Maddin)

jsfiddle

나에게 가장 적합한 솔루션(작동 가능 및 짧은 솔루션)은 다음과 같습니다.

    $(document).on('input', 'textarea', function () {
        $(this).outerHeight(38).outerHeight(this.scrollHeight); // 38 or '1em' -min-height
    }); 

페이스트(마우스도 사용), 컷, 입력으로 깜빡거리지 않고, 적당한 크기로 축소됩니다.

jsFiddle을 봐주세요.

여기서 정기선 한 척을 발견했어요.

<textarea name="text" oninput="this.style.height = ''; this.style.height = this.scrollHeight +'px'"></textarea>

없는 IE8을 할 수 .input 이벤트 표시:

var resizingTextareas = [].slice.call(document.querySelectorAll('textarea[autoresize]'));

resizingTextareas.forEach(function(textarea) {
  textarea.addEventListener('input', autoresize, false);
});

function autoresize() {
  this.style.height = 'auto';
  this.style.height = this.scrollHeight+'px';
  this.scrollTop = this.scrollHeight;
  window.scrollTo(window.scrollLeft,(this.scrollTop+this.scrollHeight));
}

이제 CSS를 몇 개만 추가하면 됩니다.

textarea[autoresize] {
  display: block;
  overflow: hidden;
  resize: none;
}

사용방법:

<textarea autoresize>Type here and I’ll resize.</textarea>

자세한 내용은 제 블로그 투고에서 보실 수 있습니다.

현재 클라이언트의 높은 값을 사용하고 있습니다.높이 및 콘텐츠 스크롤 높이.콘텐츠를 삭제하여 스크롤 하이트를 작게 하면 클라이언트 때문에 계산된 영역을 작게 할 수 없습니다.높이, 이전에 스타일별로 설정되었습니다.키가 열려 있습니다.대신 textarea.rows에서 미리 정의하거나 계산한 스크롤 하이트의 max()와 최소 높이 값을 얻을 수 있습니다.

일반적으로 폼 컨트롤의 스크롤 하이트에 의존하지 않는 것이 좋습니다.스크롤 하이트가 다른 IE 확장자 중 일부보다 널리 지원되지 않는 것을 제외하고 HTML/CSS는 폼 컨트롤의 내부 구현 방법에 대해 아무런 설명도 하지 않으며 스크롤 하이트는 의미 있는 것이 아닙니다(종래 일부 브라우저는 OS 위젯을 사용하여 CSS와 DOM의 상호 작용을 가능하게 합니다).내부가 불가능합니다.)적어도 스크롤 높이/클라이언트 스니핑효과를 활성화하기 전에 높이가 존재하는지 여부.

보다 광범위하게 기능하는 것이 중요한 경우 이 문제를 피하기 위한 다른 가능한 접근법은 텍스트 영역과 같은 너비에 같은 크기의 숨겨진 div를 사용하여 동일한 글꼴로 설정하는 것입니다.키업 시 텍스트 영역의 텍스트를 숨겨진 div의 텍스트 노드에 복사합니다(내부를 사용하는 경우 "\n"을 줄 바꿈으로 바꾸고 "</'&"를 올바르게 이스케이프합니다).HTML) 그럼 단순히 div의 오프셋을 측정하면 됩니다.키는 당신에게 필요한 키를 줄 것이다.

오토사이즈

https://github.com/jackmoore/autosize

Just works, standalone은 인기 (2018년 10월 기준 3.0k+GitHub stars, cdnjs)와 경량 (약 3.5k)입니다.데모:

<textarea id="autosize" style="width:200px;">a
J   b
c</textarea>
<script src="https://cdnjs.cloudflare.com/ajax/libs/autosize.js/4.0.2/autosize.min.js"></script>
<script>autosize(document.querySelectorAll('#autosize'));</script>

에디터를 하고 있는 는, BTW, ACE 를 합니다.maxLines: Infinity: Ace Cloud 9 Editor 콘텐츠에 맞게 높이 자동 조정

접근법으로는 '하다'를 할 수 .<span>이치노하려면 , 「 」를 합니다.contenteditable="true"제제끝끝끝끝다다

div {
  width: 200px;
}

span {
  border: 1px solid #000;
  padding: 5px;
}
<div>
  <span contenteditable="true">This text can be edited by the user</span>
</div>

이 접근법의 유일한 문제는 폼의 일부로 값을 제출하려면 JavaScript에서 직접 값을 제출해야 한다는 것입니다.그렇게 하는 것은 비교적 쉽다.를 들어나 숨김 필드를 할 수 .onsubmit에 의해, 「」의 이 됩니다.span숨김 필드로 이동하면 자동으로 폼과 함께 제출됩니다.

만족스럽다고 생각한 사람이 있나요?스크롤에 장난치지 말고 JS가 마음에 드는 건 흐릿한 곳에 데이터를 저장할 계획이라면...인기 브라우저 http://caniuse.com/ #contentable = contentatible 모두 호환성이 있는 것 같습니다.

텍스트 상자처럼 보이도록 스타일링하면 자동으로...최소 높이를 원하는 텍스트 높이로 설정하고 원하는 높이로 설정하십시오.

이 접근법의 장점은 일부 브라우저에서 저장하고 태그를 지정할 수 있다는 것입니다.

http://jsfiddle.net/gbutiri/v31o8xfo/

var _auto_value = '';
$(document).on('blur', '.autosave', function(e) {
  var $this = $(this);
  if ($this.text().trim() == '') {
    $this.html('');
  }

  // The text is here. Do whatever you want with it.
  $this.addClass('saving');

  if (_auto_value !== $this.html() || $this.hasClass('error')) {

    // below code is for example only.
    $.ajax({
      url: '/echo/json/?action=xyz_abc',
      data: 'data=' + $this.html(),
      type: 'post',
      datatype: 'json',
      success: function(d) {
        console.log(d);
        $this.removeClass('saving error').addClass('saved');
        var k = setTimeout(function() {
          $this.removeClass('saved error')
        }, 500);
      },
      error: function() {
        $this.removeClass('saving').addClass('error');
      }
    });
  } else {
    $this.removeClass('saving');
  }
}).on('focus mouseup', '.autosave', function() {
  var $this = $(this);
  if ($this.text().trim() == '') {
    $this.html('');
  }
  _auto_value = $this.html();
}).on('keyup', '.autosave', function(e) {
  var $this = $(this);
  if ($this.text().trim() == '') {
    $this.html('');
  }
});
body {
  background: #3A3E3F;
  font-family: Arial;
}

label {
  font-size: 11px;
  color: #ddd;
}

.autoheight {
  min-height: 16px;
  font-size: 16px;
  margin: 0;
  padding: 10px;
  font-family: Arial;
  line-height: 20px;
  box-sizing: border-box;
  -o-box-sizing: border-box;
  -moz-box-sizing: border-box;
  -webkit-box-sizing: border-box;
  overflow: hidden;
  display: block;
  resize: none;
  border: 0;
  outline: none;
  min-width: 200px;
  background: #ddd;
  max-height: 400px;
  overflow: auto;
}

.autoheight:hover {
  background: #eee;
}

.autoheight:focus {
  background: #fff;
}

.autosave {
  -webkit-transition: all .2s;
  -moz-transition: all .2s;
  transition: all .2s;
  position: relative;
  float: none;
}

.autoheight * {
  margin: 0;
  padding: 0;
}

.autosave.saving {
  background: #ff9;
}

.autosave.saved {
  background: #9f9;
}

.autosave.error {
  background: #f99;
}

.autosave:hover {
  background: #eee;
}

.autosave:focus {
  background: #fff;
}

[contenteditable=true]:empty:before {
  content: attr(placeholder);
  color: #999;
  position: relative;
  top: 0px;
  /*
    For IE only, do this:
    position: absolute;
    top: 10px;
    */
  cursor: text;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Your Name</label>
<div class="autoheight autosave contenteditable" contenteditable="true" placeholder="Your Name"></div>

약간 다른 접근법이 있다.

<div style="position: relative">
  <pre style="white-space: pre-wrap; word-wrap: break-word"></pre>
  <textarea style="position: absolute; top: 0; left: 0; width: 100%; height: 100%"></textarea>
</div>

입니다.textareapreCSS를 사용하다

프레임워크가 이벤트를 건드리지 않고 텍스트를 이동할 수 있는 간단한 도구를 제공한다는 장점이 있습니다. Angularθ에서는 Angularθ는 JS를 합니다.ng-model="foo" ng-trim="false"textarea그리고.ng-bind="foo + '\n'"에게pre바이올린을 보다.

그냥 확실히 해둬요pre와 같은 글꼴사이즈를 가지고 있습니다.textarea.

다음은 마우스, 키보드 단축키, 메뉴바에서 옵션 선택 여부에 관계없이 잘라내기, 붙여넣기 등의 작업을 수행합니다.몇 가지 답변은 비슷한 접근방식을 취하지만 상자 크기를 고려하지 않기 때문에 스타일을 잘못 적용합니다.overflow: hidden.

는 다음과, 하다 보면 잘 요.이것도 잘 동작합니다.max-height ★★★★★★★★★★★★★★★★★」rows★★★★★★★★★★★★★★★★★★★★★★★★★★★

function adjust() {
  var style = this.currentStyle || window.getComputedStyle(this);
  var boxSizing = style.boxSizing === 'border-box'
      ? parseInt(style.borderBottomWidth, 10) +
        parseInt(style.borderTopWidth, 10)
      : 0;
  this.style.height = '';
  this.style.height = (this.scrollHeight + boxSizing) + 'px';
};

var textarea = document.getElementById("ta");
if ('onpropertychange' in textarea) { // IE
  textarea.onpropertychange = adjust;
} else if ('oninput' in textarea) {
  textarea.oninput = adjust;
}
setTimeout(adjust.bind(textarea));
textarea {
  resize: none;
  max-height: 150px;
  border: 1px solid #999;
  outline: none;
  font: 18px sans-serif;
  color: #333;
  width: 100%;
  padding: 8px 14px;
  box-sizing: border-box;
}
<textarea rows="3" id="ta">
Try adding several lines to this.
</textarea>

을 확실히 하기 , 「 」를 .adjust다른 합니다.

  1. 크기 이벤트의 )textarea window
  2. ?textarea의 »display 변경 "에서")none에서 (숨김) ~까지block
  3. " " 의 textarea programmically(프로그래밍 변경)

「 」를 사용하고 있는 에 주의해 .window.getComputedStyle 얻어지는 것currentStyle계산 비용이 다소 많이 들 수 있으므로 결과를 캐시하는 것이 좋습니다.

IE6에 대응하고 있기 때문에, 충분히 서포트해 주셨으면 합니다.

여러 텍스트 영역에 다음 코드를 사용했습니다.텍스트 영역에서 수행된 삭제, 잘라내기 및 붙여넣기 작업도 Chrome 12, Firefox 5 및 IE 9에서 정상적으로 작동합니다.

function attachAutoResizeEvents() {
  for (i = 1; i <= 4; i++) {
    var txtX = document.getElementById('txt' + i)
    var minH = txtX.style.height.substr(0, txtX.style.height.indexOf('px'))
    txtX.onchange = new Function("resize(this," + minH + ")")
    txtX.onkeyup = new Function("resize(this," + minH + ")")
    txtX.onchange(txtX, minH)
  }
}

function resize(txtX, minH) {
  txtX.style.height = 'auto' // required when delete, cut or paste is performed
  txtX.style.height = txtX.scrollHeight + 'px'
  if (txtX.scrollHeight <= minH)
    txtX.style.height = minH + 'px'
}
window.onload = attachAutoResizeEvents
textarea {
  border: 0 none;
  overflow: hidden;
  outline: none;
  background-color: #eee
}
<textarea style='height:100px;font-family:arial' id="txt1"></textarea>
<textarea style='height:125px;font-family:arial' id="txt2"></textarea>
<textarea style='height:150px;font-family:arial' id="txt3"></textarea>
<textarea style='height:175px;font-family:arial' id="txt4"></textarea>

조금 수정했습니다.오페라에서 완벽하게 동작

  $('textarea').bind('keyup keypress', function() {
      $(this).height('');
      var brCount = this.value.split('\n').length;
      this.rows = brCount+1; //++ To remove twitching
      var areaH = this.scrollHeight,
          lineHeight = $(this).css('line-height').replace('px',''),
          calcRows = Math.floor(areaH/lineHeight);
      this.rows = calcRows;
  });

여기 panzi의 답변에 대한 angularjs 지시가 있습니다.

 module.directive('autoHeight', function() {
        return {
            restrict: 'A',
            link: function(scope, element, attrs) {
                element = element[0];
                var resize = function(){
                    element.style.height = 'auto';
                    element.style.height = (element.scrollHeight)+'px';
                };
                element.addEventListener('change', resize, false);
                element.addEventListener('cut',    resize, false);
                element.addEventListener('paste',  resize, false);
                element.addEventListener('drop',   resize, false);
                element.addEventListener('keydown',resize, false);

                setTimeout(resize, 100);
            }
        };
    });

HTML:

<textarea ng-model="foo" auto-height></textarea>

나는 이것을 jquery로 구현하는 짧고 올바른 방법을 알고 있다.추가 숨김 div가 필요하지 않으며 대부분의 브라우저에서 작동합니다.

<script type="text/javascript">$(function(){
$("textarea").live("keyup keydown",function(){
var h=$(this);
h.height(60).height(h[0].scrollHeight);//where 60 is minimum height of textarea
});});

</script>

여기 있는 답들 중 일부는 패딩을 설명하지 않습니다.

넘어가지 않는 최대 높이가 있다고 가정하면 다음과 같이 할 수 있습니다.

    // obviously requires jQuery

    // element is the textarea DOM node

    var $el = $(element);
    // inner height is height + padding
    // outerHeight includes border (and possibly margins too?)
    var padding = $el.innerHeight() - $el.height();
    var originalHeight = $el.height();

    // XXX: Don't leave this hardcoded
    var maxHeight = 300;

    var adjust = function() {
        // reset it to the original height so that scrollHeight makes sense
        $el.height(originalHeight);

        // this is the desired height (adjusted to content size)
        var height = element.scrollHeight - padding;

        // If you don't want a maxHeight, you can ignore this
        height = Math.min(height, maxHeight);

        // Set the height to the new adjusted height
        $el.height(height);
    }

    // The input event only works on modern browsers
    element.addEventListener('input', adjust);

누가 이런 식으로 언급했는지 모르겠지만 경우에 따라 행으로 높이 크기를 조정할 수 있습니다. 속성

textarea.setAttribute('rows',breaks);

데모

한층 더 심플하고 깔끔한 어프로치는 다음과 같습니다.

// adjust height of textarea.auto-height
$(document).on( 'keyup', 'textarea.auto-height', function (e){
    $(this).css('height', 'auto' ); // you can have this here or declared in CSS instead
    $(this).height( this.scrollHeight );
}).keyup();

// 및 CSS

textarea.auto-height {
    resize: vertical;
    max-height: 600px; /* set as you need it */
    height: auto;      /* can be set here of in JS */
    overflow-y: auto;
    word-wrap:break-word
}

은 '아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아.auto-height 쪽에도 속하다textarea타겟이 되고 싶군요

FF, Chrome 및 Safari에서 테스트 완료.어떤 이유에서든, 이것이 당신에게 맞지 않으면 알려주세요.하지만 이게 내가 찾은 가장 깔끔하고 간단한 방법이야.그리고 그것은 매우 효과적이다!d

하여 JQuery를 할 수 .textarea「 」:

$(document).find('textarea').each(function () {
  var offset = this.offsetHeight - this.clientHeight;

  $(this).on('keyup input focus', function () {
    $(this).css('height', 'auto').css('height', this.scrollHeight + offset);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div>
<textarea name="note"></textarea>
<div>

Angular의 새로운 버전에서도 같은 것을 달성하고 싶은 사람.

textArea elementRef를 가져옵니다.

@ViewChild('textArea', { read: ElementRef }) textArea: ElementRef;

public autoShrinkGrow() {
    textArea.style.overflow = 'hidden';
    textArea.style.height = '0px';
    textArea.style.height = textArea.scrollHeight + 'px';
}

<textarea (keyup)="autoGrow()" #textArea></textarea>

데 이 될 수 다른 했습니다.overflow:scroll위의 방법을 확장하여 전술한 사용 사례를 달성할 수 있습니다.

  public autoGrowShrinkToCertainHeight() {
    const textArea = this.textArea.nativeElement;
    if (textArea.scrollHeight > 77) {
      textArea.style.overflow = 'auto';
      return;
    }
    else {
      textArea.style.overflow = 'hidden';
      textArea.style.height = '0px';
      textArea.style.height = textArea.scrollHeight + 'px';
    }
  }

이 코드는 붙여넣기에 사용할 수 있으며 delete도 선택합니다.

onKeyPressTextMessage = function(){
			var textArea = event.currentTarget;
    	textArea.style.height = 'auto';
    	textArea.style.height = textArea.scrollHeight + 'px';
};
<textarea onkeyup="onKeyPressTextMessage(event)" name="welcomeContentTmpl" id="welcomeContent" onblur="onblurWelcomeTitle(event)" rows="2" cols="40" maxlength="320"></textarea>

여기 JSFiddle이 있습니다.

http://javierjulio.github.io/textarea-autosize의 javascript 라이브러리를 추천합니다.

코멘트별로 플러그인 사용에 대한 코드 블록 예를 추가합니다.

<textarea class="js-auto-size" rows="1"></textarea>

<script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
<script src="jquery.textarea_autosize.min.js"></script>
<script>
$('textarea.js-auto-size').textareaAutoSize();
</script>

필요한 최소 CSS:

textarea {
  box-sizing: border-box;
  max-height: 160px; // optional but recommended
  min-height: 38px;
  overflow-x: hidden; // for Firefox (issue #5)
}

qQuery를 사용하는 MakeTextAreaResisable

function MakeTextAreaResisable(id) {
    var o = $(id);
    o.css("overflow-y", "hidden");

    function ResizeTextArea() {
        o.height('auto');
        o.height(o[0].scrollHeight);
    }

    o.on('change', function (e) {
        ResizeTextArea();
    });

    o.on('cut paste drop keydown', function (e) {
        window.setTimeout(ResizeTextArea, 0);
    });

    o.focus();
    o.select();
    ResizeTextArea();
}

어떤 대답도 효과가 없는 것 같다.하지만 https://coderwall.com/p/imkqoq/resize-textarea-to-fit-content이 도움이 됩니다.

$('#content').on( 'change keyup keydown paste cut', 'textarea', function (){
    $(this).height(0).height(this.scrollHeight);
}).find( 'textarea' ).change();

구현은 매우 간단합니다.입력 행의 수를 세어 주세요(텍스트 영역임을 나타내기 위해 최소 2행).

textarea.rows = Math.max(2, textarea.value.split("\n").length) // # oninput

자극에 의한 완전한 작업 예: https://jsbin.com/kajosolini/1/edit?html,js,output

(예를 들어 브라우저의 수동 크기 조정 핸들과 함께 작동합니다.)

인정된 답변은 정상적으로 동작하고 있습니다.하지만 이 단순한 기능에는 많은 코드가 있습니다.아래 코드가 유효합니다.

   $(document).on("keypress", "textarea", function (e) {
    var height = $(this).css("height");
    var iScrollHeight = $(this).prop("scrollHeight");
    $(this).css('height',iScrollHeight);
    });

scrollHeight를 신뢰할 수 있는 경우:

textarea.onkeyup=function() {
  this.style.height='';
  this.rows=this.value.split('\n').length;
  this.style.height=this.scrollHeight+'px';
}

다음은 MVC HTML Helper for TextArea를 사용하는 동안 수행한 작업입니다.텍스트 영역 요소가 상당히 많아서 모델 ID를 사용하여 구분해야 했습니다.

 @Html.TextAreaFor(m => m.Text, 2, 1, new { id = "text" + Model.Id, onkeyup = "resizeTextBox(" + Model.Id + ");" })

스크립트에는 다음과 같은 내용이 추가되어 있습니다.

   function resizeTextBox(ID) {            
        var text = document.getElementById('text' + ID);
        text.style.height = 'auto';
        text.style.height = text.scrollHeight + 'px';            
    }

IE10 및 Firefox23에서 테스트했습니다.

언급URL : https://stackoverflow.com/questions/454202/creating-a-textarea-with-auto-resize

반응형