입력 할 때 html 텍스트 입력 필드가 커지도록합니까?


81

다음과 같이 CSS로 초기 텍스트 입력 크기를 설정할 수 있습니다.

width: 50px;

그러나 예를 들어 200px에 도달 할 때까지 입력하면 성장하고 싶습니다. 이것은 가급적 javascript없이 직접 CSS, html로 수행 할 수 있습니까?

물론 js / jquery 솔루션도 게시하십시오. 그러나 이것이 없이도 가능하다면 훌륭합니다.

내 시도 :

http://jsfiddle.net/jszjz/2/


이 질문이 도움이 될 것이라고 생각합니다 : stackoverflow.com/questions/1288297/…
Curt

기록을 위해, 내가 아니었다. 내가 연결 한 것과 유사하지만 유효한 질문처럼 보입니다.
Curt

Andre : 의견을 건설적으로 유지하십시오.
Seth

1
contenteditable이있는 단락을 사용할 수 있습니다. 자체적으로 입력하면 확장됩니다.
Costa

답변:


107

다음은 CSS 및 Content Editable 만있는 예입니다 .

jsFiddle 예

CSS

span 
{
    border: solid 1px black;
}
div 
{
    max-width: 200px;   
}

HTML

<div>
    <span contenteditable="true">sdfsd</span>
</div>

4
예. IE6-9, 최신 Opera, Firefox 및 Chrome 및 OMG에서 시도해 보았습니다. 모든 곳에서 작동했습니다!
Stann

4
Chrome에서 이것은 최대 너비에 도달하면 요소를 행 아래로 확장합니다. 입력이 양식의 일부인 경우에도 작동하지 않습니다.
Paul

5
여러 줄의 입력 필드 (사용자 정의 줄 바꿈)의 경우, 교체 span에 의해 div. word-wrap: break-word필요하거나 더 긴 단어 max-width가 div 상자를 넘칠 것임을 유의하십시오 . jsfiddle.net/YZPmC/157
CodeManX

6
복사 및 붙여 넣기를 통해 contenteditable 범위에 들어갈 수있는 원치 않는 html을 스크럽해야합니다.
Brian Peacock

3
양식과 함께 보내나요?
토마스 Zato - 분석 재개 모니카

38

나는 당신을 위해 이것을 썼습니다, 나는 당신이 그것을 좋아하기를 바랍니다 :) 그것이 크로스 브라우저라는 보장은 없지만 나는 그것이 있다고 생각합니다 :)

(function(){
    var min = 100, max = 300, pad_right = 5, input = document.getElementById('adjinput');

    input.style.width = min+'px';
    input.onkeypress = input.onkeydown = input.onkeyup = function(){
        var input = this;
        setTimeout(function(){
            var tmp = document.createElement('div');
            tmp.style.padding = '0';
            if(getComputedStyle)
                tmp.style.cssText = getComputedStyle(input, null).cssText;
            if(input.currentStyle)
                tmp.style.cssText = input.currentStyle.cssText;
            tmp.style.width = '';
            tmp.style.position = 'absolute';
            tmp.innerHTML = input.value.replace(/&/g, "&amp;")
                                       .replace(/</g, "&lt;")
                                       .replace(/>/g, "&gt;")
                                       .replace(/"/g, "&quot;")
                                       .replace(/'/g, "&#039;")
                                       .replace(/ /g, '&nbsp;');
            input.parentNode.appendChild(tmp);
            var width = tmp.clientWidth+pad_right+1;
            tmp.parentNode.removeChild(tmp);
            if(min <= width && width <= max)
                input.style.width = width+'px';
        }, 1);
    }
})();

JSFiddle


이것에 감사드립니다. js가 필요하지 않은 contenteditable 속성으로 수행하기로 결정했습니다.
Stann

34
"나는 당신을 위해 이것을 썼습니다". 노력에 대한 +1 :)
Kevin Martin Jose

어떻게 내가이 더 이상 1 (4) 입력 타겟팅 할 수 않습니다id='adjinput'
teachtyler

내가 좋아하는 매우 창조적 인
데릭

2
이것은 콘텐츠 변경이 키보드 사용에 의해서만 발생한다고 가정합니다.
ceving

7

표시 할 범위를 설정하면 : 인라인 블록, 자동 가로 및 세로 크기 조정이 매우 잘 작동합니다.

<span contenteditable="true" 
      style="display: inline-block;
             border: solid 1px black;
             min-width: 50px; 
             max-width: 200px">
</span>


6

입력의 크기 속성을 프로그래밍 방식으로 수정하는 것은 어떻습니까?

의미 론적으로 (imo),이 솔루션은 사용자 입력을 위해 입력 필드를 사용하지만 약간의 jQuery를 도입하기 때문에 허용 된 솔루션보다 낫습니다. Soundcloud는 태그 지정을 위해 이와 유사한 작업을 수행합니다.

<input size="1" />

$('input').on('keydown', function(evt) {
    var $this = $(this),
        size = parseInt($this.attr('size'), 10),
        isValidKey = (evt.which >= 65 && evt.which <= 90) || // a-zA-Z
                     (evt.which >= 48 && evt.which <= 57) || // 0-9
                     evt.which === 32;

    if ( evt.which === 8 && size > 0 ) {
        // backspace
        $this.attr('size', size - 1);
    } else if ( isValidKey ) {
        // all other keystrokes
        $this.attr('size', size + 1);
    }
});

http://jsfiddle.net/Vu9ZT/


2
이것은
size-

3
나는 계산 value.length이 더 쉽고 신뢰할 수 있다고 생각합니다 .
토마스 Zato - 분석 재개 모니카

1
Delete 키는이 성장한다한다
Ricca

3

몇 가지가 떠 오릅니다.

onkeydown텍스트 필드에서 핸들러를 사용 하고 텍스트 *를 측정 한 다음 그에 따라 텍스트 상자 크기를 늘립니다.

첨부 :focus너비가 더 큰 텍스트 상자에 CSS 클래스를 하십시오. 그러면 초점을 맞출 때 상자가 더 커집니다. 그것은 정확히 당신이 요구하는 것은 아니지만 유사합니다.

* 자바 스크립트에서 텍스트를 측정하는 것은 간단하지 않습니다. 이 질문 에서 몇 가지 아이디어를 확인하십시오 .


지금까지 최고의 답변입니다. :focus { width: 100% }
oldboy

3

보낸 사람 : 텍스트 필드 용 jQuery 자동 증가 플러그인이 있습니까?


여기에서 데모보기 : http://jsbin.com/ahaxe

플러그인 :

(function($){

    $.fn.autoGrowInput = function(o) {

        o = $.extend({
            maxWidth: 1000,
            minWidth: 0,
            comfortZone: 70
        }, o);

        this.filter('input:text').each(function(){

            var minWidth = o.minWidth || $(this).width(),
                val = '',
                input = $(this),
                testSubject = $('<tester/>').css({
                    position: 'absolute',
                    top: -9999,
                    left: -9999,
                    width: 'auto',
                    fontSize: input.css('fontSize'),
                    fontFamily: input.css('fontFamily'),
                    fontWeight: input.css('fontWeight'),
                    letterSpacing: input.css('letterSpacing'),
                    whiteSpace: 'nowrap'
                }),
                check = function() {

                    if (val === (val = input.val())) {return;}

                    // Enter new content into testSubject
                    var escaped = val.replace(/&/g, '&amp;').replace(/\s/g,'&nbsp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
                    testSubject.html(escaped);

                    // Calculate new width + whether to change
                    var testerWidth = testSubject.width(),
                        newWidth = (testerWidth + o.comfortZone) >= minWidth ? testerWidth + o.comfortZone : minWidth,
                        currentWidth = input.width(),
                        isValidWidthChange = (newWidth < currentWidth && newWidth >= minWidth)
                                             || (newWidth > minWidth && newWidth < o.maxWidth);

                    // Animate width
                    if (isValidWidthChange) {
                        input.width(newWidth);
                    }

                };

            testSubject.insertAfter(input);

            $(this).bind('keyup keydown blur update', check);

        });

        return this;

    };

})(jQuery);

2

여기에서 이와 같은 것을 시도 할 수 있습니다.

편집 : 수정 된 예제 (하나의 새로운 솔루션 추가) http://jsfiddle.net/jszjz/10/

코드 설명

var jqThis = $('#adjinput'), //object of the input field in jQuery
    fontSize = parseInt( jqThis.css('font-size') ) / 2, //its font-size
    //its min Width (the box won't become smaller than this
    minWidth= parseInt( jqThis.css('min-width') ), 
    //its maxWidth (the box won't become bigger than this)
    maxWidth= parseInt( jqThis.css('max-width') );

jqThis.bind('keydown', function(e){ //on key down
   var newVal = (this.value.length * fontSize); //compute the new width

   if( newVal  > minWidth && newVal <= maxWidth ) //check to see if it is within Min and Max
       this.style.width = newVal + 'px'; //update the value.
});

CSS도 꽤 간단합니다.

#adjinput{
    max-width:200px !important;
    width:40px;
    min-width:40px;
    font-size:11px;
}

편집 : 또 다른 해결책은 사용자가 원하는 것을 입력하고 흐림 (초점)하고 문자열을 (동일한 글꼴 크기로) div에 배치하고 div의 너비를 계산 한 다음 멋진 애니메이션을 사용하는 것입니다. 여유 효과는 입력 필드 너비를 업데이트합니다. 유일한 단점은 사용자가 입력하는 동안 입력 필드가 "작게"유지된다는 것입니다. 또는 시간 제한을 추가 할 수 있습니다. :) 위의 바이올린에서도 이러한 종류의 솔루션을 확인할 수 있습니다!


font-size완벽한 솔루션이 아닙니다. 나쁘지 않고 확실히 투표 할 가치가 없지만 문자를 i여러 번 입력 하면 크기가 매우 왜곡 된 결과를 볼 수 있습니다. 이에 대한 수정 사항은 내 대답을 참조하십시오.
Paul

글꼴 크기를 사용하지 않고 부드러움을 선택하는 내 바이올린의 두 번째 예제를 참조하십시오. 첫 번째는 질문자가 원하는 것을 유지하면서 속도와 속도만을 위해 추가되었습니다. div를 생성하고 텍스트를 추가하고 너비를 계산하는 등의 작업은 매번 "무거운"것처럼 보입니다.
Pantelis

이유는 잘 모르겠지만 두 번째 예는 전혀 크기가 조정되지 않습니다. 또한 내 솔루션 (임시 div 등을 생성 함)은 평균 최신 컴퓨터의 최신 브라우저에서 초당 약 800 회 실행될 수 있으며 99.5에서 초당 100 회보다 훨씬 느려지지 않을 수도 있습니다. 현재 여전히 사용중인 컴퓨터의 비율)
Paul

2

나는 이것이 심각하게 오래된 게시물이라는 것을 알고 있지만 어쨌든 내 대답은 다른 사람들에게 유용 할 수 있으므로 여기에 있습니다. contenteditable div에 대한 CSS 스타일 정의가 높이 200 대신 200의 최소 높이를 가지면 div가 자동으로 확장된다는 것을 발견했습니다.


1

당신은 단지 성장에 관심이 있다면, 당신은 업데이트 할 수 있습니다 width에를 scrollWidth, 때마다의 내용 input요소가 변경.

document.querySelectorAll('input[type="text"]').forEach(function(node) {
  node.onchange = node.oninput = function() {
    node.style.width = node.scrollWidth+'px';
  };
});

그러나 이것은 요소를 축소하지 않습니다.


1

물론 사용하는 접근 방식은 최종 목표가 무엇인지에 따라 다릅니다. 양식과 함께 결과를 제출하려는 경우 기본 양식 요소를 사용하면 제출을 위해 스크립팅을 사용할 필요가 없습니다. 또한 스크립팅이 꺼져 있으면 멋진 성장 축소 효과없이 폴 백이 여전히 작동합니다. contenteditable 요소 에서 일반 텍스트를 얻으려면 항상 node.textContent 와 같은 스크립팅을 사용 하여 브라우저가 사용자 입력에 삽입하는 html을 제거 할 수 있습니다 .

이 버전은 이전 게시물 중 일부를 약간 개선 한 기본 양식 요소를 사용합니다.

콘텐츠도 축소 할 수 있습니다.

더 나은 제어를 위해 CSS와 함께 사용하십시오.

<html>

<textarea></textarea>
<br>
<input type="text">


<style>

textarea {
  width: 300px;
  min-height: 100px;
}

input {
  min-width: 300px;
}


<script>

document.querySelectorAll('input[type="text"]').forEach(function(node) {
  var minWidth = parseInt(getComputedStyle(node).minWidth) || node.clientWidth;
  node.style.overflowX = 'auto'; // 'hidden'
  node.onchange = node.oninput = function() {
    node.style.width = minWidth + 'px';
    node.style.width = node.scrollWidth + 'px';
  };
});

<textarea> 요소와 비슷한 것을 사용할 수 있습니다.

document.querySelectorAll('textarea').forEach(function(node) {
  var minHeight = parseInt(getComputedStyle(node).minHeight) || node.clientHeight;
  node.style.overflowY = 'auto'; // 'hidden'
  node.onchange = node.oninput = function() {
    node.style.height = minHeight + 'px';
    node.style.height = node.scrollHeight + 'px';
  };
});

Chrome에서는 깜박이지 않으며 다른 브라우저에서는 결과가 다를 수 있으므로 테스트하세요.


0

나를 위해 일한 방법이 있습니다. 필드에 입력하면 해당 텍스트를 숨겨진 범위에 넣은 다음 새 너비를 가져와 입력 필드에 적용합니다. 모든 입력을 지울 때 입력이 사실상 사라지는 것을 방지하기 위해 입력에 따라 확장 및 축소됩니다. Chrome에서 테스트되었습니다. (편집 :이 편집 당시 Safari, Firefox 및 Edge에서 작동합니다)

function travel_keyup(e)
{
    if (e.target.value.length == 0) return;
    var oSpan=document.querySelector('#menu-enter-travel span');
    oSpan.textContent=e.target.value;
    match_span(e.target, oSpan);
}
function travel_keydown(e)
{
    if (e.key.length == 1)
    {
        if (e.target.maxLength == e.target.value.length) return;
        var oSpan=document.querySelector('#menu-enter-travel span');
        oSpan.textContent=e.target.value + '' + e.key;
        match_span(e.target, oSpan);
    }
}
function match_span(oInput, oSpan)
{
    oInput.style.width=oSpan.getBoundingClientRect().width + 'px';
}

window.addEventListener('load', function()
{
    var oInput=document.querySelector('#menu-enter-travel input');
    oInput.addEventListener('keyup', travel_keyup);
    oInput.addEventListener('keydown', travel_keydown);

    match_span(oInput, document.querySelector('#menu-enter-travel span'));
});
#menu-enter-travel input
{
	width: 8px;
}
#menu-enter-travel span
{
	visibility: hidden;
    position: absolute;
    top: 0px;
    left: 0px;
}
<div id="menu-enter-travel">
<input type="text" pattern="^[0-9]{1,4}$" maxlength="4">KM
<span>9</span>
</div>


0

ch 측정 (모노 스페이스)을 사용할 수 있다면 내가하려는 작업을 완전히 해결했습니다.

onChange(e => {
    e.target.style.width = `${e.target.length}ch`;
})

이것은 정확히 필요한 것이었지만 동적 너비 글꼴 패밀리에서 작동하는지 확실하지 않습니다.


0

입력 또는 텍스트 영역에서 작동하는 솔루션을 엄격하게 찾는 사람들에게 이것은 내가 본 것 중 가장 간단한 솔루션입니다. CSS 몇 줄과 JS 한 줄만.

JavaScript는 입력 값과 동일한 요소에 data- * 속성을 설정합니다. 입력은 CSS 그리드 내에서 설정되며 해당 그리드는 해당 data- * 속성을 콘텐츠로 사용하는 의사 요소입니다. 그 내용은 입력 값에 따라 그리드를 적절한 크기로 늘리는 것입니다.


당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.