program story

텍스트 필드에 대한 jQuery 자동 증가 플러그인이 있습니까?

inputbox 2020. 11. 13. 08:11
반응형

텍스트 필드에 대한 jQuery 자동 증가 플러그인이 있습니까?


textarea 자동 성장을위한 다양한 플러그인을 찾았 지만 입력 텍스트 필드는 없습니다. 아무도 존재하는지 아는 사람이 있습니까?


다음은 원하는 작업을 수행 할 플러그인입니다.

편집 : Mathias의 의견에 따라 플러그인을 수정했습니다. :)

여기에서 데모보기 : http://jsfiddle.net/rRHzY

플러그인 :

(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);

GitHub에 jQuery 플러그인이 있습니다 : https://github.com/MartinF/jQuery.Autosize.Input

James 답변과 동일한 접근 방식을 사용하지만 주석에 언급 된 일부 변경 사항이 있습니다.

여기에서 라이브 예제를 볼 수 있습니다 : http://jsfiddle.net/mJMpw/6/

예:

<input type="text" value="" placeholder="Autosize" data-autosize-input='{ "space": 40 }' />

input[type="data-autosize-input"] {
  width: 90px;
  min-width: 90px;
  max-width: 300px;
  transition: width 0.25s;    
}

CSS를 사용하여 최소 / 최대 너비를 설정하고 멋진 효과를 원한다면 너비에 전환을 사용하십시오.

입력 요소의 data-autosize-input 속성에 대한 json 표기법의 값으로 끝까지의 공간 / 거리를 지정할 수 있습니다.

물론 jQuery를 사용하여 초기화 할 수도 있습니다.

$("selector").autosizeInput();

좋은 플러그인, 감사합니다! 그래도 내 프로젝트에서 더 잘 작동하는 것 같은 두 가지를 변경했습니다.

  1. '메서드 또는 속성 액세스에 대한 예기치 않은 호출'이 발생하지 않도록 TESTER 태그를 DIV로 변경했습니다. IE8에서 (데모가 IE8에서 작동하더라도. 사용자 정의 HTML 태그를 사용하는 특별한 이유가 있습니까?
  2. 코드 끝 부분에있는 bind 문 다음에, 텍스트 상자에 이미 내용이있는 경우 페이지를로드 한 직후 텍스트 상자의 크기를 조정하기 위해 check () 호출을 추가했습니다.

도움이 되었기를 바랍니다.


James의 훌륭한 플러그인에 대한 작은 개선 사항을 공유하고 싶었습니다. tester 요소의 CSS 선언에 다음 코드를 추가하여 텍스트 들여 쓰기를 설명합니다.

textIndent: 0

그것이 없으면 어떤 상황에서는 tester 요소가 다른 곳에서 실수로 텍스트 들여 쓰기를 상속하여 입력 크기를 떨어 뜨릴 수 있습니다.

JP와 마찬가지로 입력을 처음부터 올바른 크기로 조정하고 싶었습니다. "trigger ( 'keyup')"를 autoGrowInput 메서드 호출에 연결하여 약간 다르게 수행했습니다. 예 :

$('#contact_form').autoGrowInput({comfortZone: 7, minWidth: 10, maxWidth: 200}).trigger('keyup');

참고로 저는이 사이트에 순전히 James의 솔루션에 대한 의견을 제시하기 위해 가입했으며 시작할 평판 포인트가 충분하지 않아서 할 수 없다는 사실에 약간 짜증이났습니다. 내가 뭔가를 놓친 경우 미안하지만 James의 솔루션에 더 적절하게보다는 주 질문에 대한 의견을 게시해야 함을 의미하는 것 같습니다.


나는 또한 교체했다

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

...에

$(this).bind('keyup blur update', check).bind('keydown', function() {
    setTimeout(check);
});

브라우저에서 다시 렌더링 한 직후에 필드 크기를 조정하기 위해. 그것은 수다쟁이에서 들판을 없앨 것입니다.


이 동작을 재현하는 텍스트 입력 용 플러그인을 만들었습니다. 다른 독특한 기능이 있습니다. 예제플러그인 문서수 있습니다 . @james 대답에는 큰 텍스트를 입력에 붙여 넣는 데 몇 가지 문제가 있습니다. 이를 고치기 위해 그의 코드를 약간 수정했습니다. 다음은 이 예에 대한 데모 입니다.

(function($){        
    $.fn.autoGrowInput = function(o) {

        o = $.extend({
            maxWidth: 200,
            minWidth: 1,
            comfortZone: 1,
          width: 1
        }, o);

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

            var minWidth = o.minWidth || $(this).width(),
                maxWidth = o.maxWidth,
                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,
                    currentWidth = input.width();

                   if (testerWidth < minWidth) {
                       newWidth = minWidth;
                   } else if (testerWidth > maxWidth) {
                       newWidth = maxWidth;
                   } 

                   input.width(newWidth + o.comfortZone);  
            };

            testSubject.insertAfter(input);

            $(this).bind('input', check);

        });

        return this;

    };

})(jQuery);

텍스트 상자의 문자열이 너비를 넘어서 확장 될 때 텍스트 상자가 커지기를 원한다면, 아마도 이와 같은 것이 효과가있을 것입니다. 텍스트 상자의 크기 속성을 감지합니다. 문자열의 길이가 해당 속성을 초과하면 키업시 텍스트 상자를 문자열의 길이로 확장합니다.

아래 스크립트에서 "#test"는 텍스트 상자 ID입니다.

<script language="javascript" type="text/javascript">
$(document).ready(function(){
    $("#test").keyup(function(){
        if($("#test").attr("size") < $("#test").val().length){
            size = $("#test").val().length;
            $("#test").attr("size",size);
        }
    })
});
</script>

Funny enough in IE overflow: visible is taken very seriously. You can achieve this effect by applying overflow: visible on your input elements. Not sure if any similar CSS tricks exist for modern browsers.


Awsome plugin James ! Thanks. I did add the check suggestion in the end by JP though very effective .

Also I added a some changes on my part. I wanted to set the size for the input to the maximum size if the changed width exceeded the maxWidth so I added :

else if (widthexceeds){
    input.width(o.maxWidth);
}

below the if check for isValidWidthChange where widthexceeds = newWidth > o.maxWidth


I created a plugin called input-autogrow to solve this problem for my own projects. This plugin was originally based off of James answer but has been improved in many ways.

https://github.com/westonganger/input-autogrow

input-autogrow is a plugin for autogrowing inputs. This plugin is different from others because most usually target textarea tags, this library is instead targeted at input tags. Requires a DOM library such as jQuery, Zepto, or any that supports $.fn plugins.

Here are some usage examples.

/* Makes elements readonly if they already have the readonly attribute */
$('input.autogrow').inputAutogrow();

/* Manually trigger update */
$('input.autogrow').trigger('autogrow');
/* or */
$('input.autogrow').trigger('change');

/* Custom Options */
$('input.autogrow').inputAutogrow({maxWidth: 500, minWidth: 25, trailingSpace: 10});

/* Remove autogrow from input */
$('input.autogrow').inputAutogrow('destroy');

참고URL : https://stackoverflow.com/questions/931207/is-there-a-jquery-autogrow-plugin-for-text-fields

반응형