복붙노트

[JQUERY] 채우기 고정 된 크기의 컨테이너에 크기 자동 동적 텍스트

JQUERY

채우기 고정 된 크기의 컨테이너에 크기 자동 동적 텍스트

해결법


  1. 1.감사 공격. 내가 jQuery를 사용하고 싶었다.

    감사 공격. 내가 jQuery를 사용하고 싶었다.

    당신은 올바른 방향으로 절 지적, 이것은 내가 함께 끝난 것입니다 :

    여기에 플러그인에 대한 링크는 다음과 같습니다 https://plugins.jquery.com/textfill/ 그리고 소스에 대한 링크 : http://jquery-textfill.github.io/

    ;(function($) {
        $.fn.textfill = function(options) {
            var fontSize = options.maxFontPixels;
            var ourText = $('span:visible:first', this);
            var maxHeight = $(this).height();
            var maxWidth = $(this).width();
            var textHeight;
            var textWidth;
            do {
                ourText.css('font-size', fontSize);
                textHeight = ourText.height();
                textWidth = ourText.width();
                fontSize = fontSize - 1;
            } while ((textHeight > maxHeight || textWidth > maxWidth) && fontSize > 3);
            return this;
        }
    })(jQuery);
    
    $(document).ready(function() {
        $('.jtextfill').textfill({ maxFontPixels: 36 });
    });
    

    내 HTML은 다음과 같이이다

    <div class='jtextfill' style='width:100px;height:50px;'>
        <span>My Text Here</span>
    </div>
    

    이것은 내 첫 번째 jQuery 플러그인입니다, 그래서 그것이 있어야로 좋은으로 아마 아니다. 포인터는 확실히 환영합니다.


  2. 2.내가 루프 대신 간단한 수학을 사용하는 내 자신을했다, 그래서 나는 인해 나쁜 성능을 적절한 충분하기 이전 솔루션 중 하나를 찾을 수 없습니다. 뿐만 아니라 모든 브라우저에서 잘 작동합니다.

    내가 루프 대신 간단한 수학을 사용하는 내 자신을했다, 그래서 나는 인해 나쁜 성능을 적절한 충분하기 이전 솔루션 중 하나를 찾을 수 없습니다. 뿐만 아니라 모든 브라우저에서 잘 작동합니다.

    이 성능 테스트 케이스에 따르면, 그것은 훨씬 더 빨리 다음 다른 솔루션은 여기에서 찾을 수 있습니다.

    (function($) {
        $.fn.textfill = function(maxFontSize) {
            maxFontSize = parseInt(maxFontSize, 10);
            return this.each(function(){
                var ourText = $("span", this),
                    parent = ourText.parent(),
                    maxHeight = parent.height(),
                    maxWidth = parent.width(),
                    fontSize = parseInt(ourText.css("fontSize"), 10),
                    multiplier = maxWidth/ourText.width(),
                    newSize = (fontSize*(multiplier-0.1));
                ourText.css(
                    "fontSize", 
                    (maxFontSize > 0 && newSize > maxFontSize) ? 
                        maxFontSize : 
                        newSize
                );
            });
        };
    })(jQuery);
    

    당신이 기여하고 싶다면 나는 요점이 추가되었습니다.


  3. 3.나는이 답변 (감사합니다!) 얻을 가끔 upvotes을 사랑하는만큼,이 정말이 문제에 대한 가장 큰 방법이 아니다. 여기에 다른 훌륭한 답변의 일부, 반복없이 솔루션을 발견, 특히 사람을 확인하시기 바랍니다.

    나는이 답변 (감사합니다!) 얻을 가끔 upvotes을 사랑하는만큼,이 정말이 문제에 대한 가장 큰 방법이 아니다. 여기에 다른 훌륭한 답변의 일부, 반복없이 솔루션을 발견, 특히 사람을 확인하시기 바랍니다.

    그럼에도 불구하고, 참조를 위해, 여기 내 원래의 대답입니다 :

    <html>
    <head>
    <style type="text/css">
        #dynamicDiv
        {
        background: #CCCCCC;
        width: 300px;
        height: 100px;
        font-size: 64px;
        overflow: hidden;
        }
    </style>
    
    <script type="text/javascript">
        function shrink()
        {
            var textSpan = document.getElementById("dynamicSpan");
            var textDiv = document.getElementById("dynamicDiv");
    
            textSpan.style.fontSize = 64;
    
            while(textSpan.offsetHeight > textDiv.offsetHeight)
            {
                textSpan.style.fontSize = parseInt(textSpan.style.fontSize) - 1;
            }
        }
    </script>
    
    </head>
    <body onload="shrink()">
        <div id="dynamicDiv"><span id="dynamicSpan">DYNAMIC FONT</span></div>
    </body>
    </html>
    

    그리고 여기에 클래스가있는 버전입니다 :

    <html>
    <head>
    <style type="text/css">
    .dynamicDiv
    {
        background: #CCCCCC;
        width: 300px;
        height: 100px;
        font-size: 64px;
        overflow: hidden;
    }
    </style>
    
    <script type="text/javascript">
        function shrink()
        {
            var textDivs = document.getElementsByClassName("dynamicDiv");
            var textDivsLength = textDivs.length;
    
            // Loop through all of the dynamic divs on the page
            for(var i=0; i<textDivsLength; i++) {
    
                var textDiv = textDivs[i];
    
                // Loop through all of the dynamic spans within the div
                var textSpan = textDiv.getElementsByClassName("dynamicSpan")[0];
    
                // Use the same looping logic as before
                textSpan.style.fontSize = 64;
    
                while(textSpan.offsetHeight > textDiv.offsetHeight)
                {
                    textSpan.style.fontSize = parseInt(textSpan.style.fontSize) - 1;
                }
    
            }
    
        }
    </script>
    
    </head>
    <body onload="shrink()">
        <div class="dynamicDiv"><span class="dynamicSpan">DYNAMIC FONT</span></div>
        <div class="dynamicDiv"><span class="dynamicSpan">ANOTHER DYNAMIC FONT</span></div>
        <div class="dynamicDiv"><span class="dynamicSpan">AND YET ANOTHER DYNAMIC FONT</span></div>
    </body>
    </html>
    

  4. 4.다른 답변의 대부분은이 사업부에 맞을 때까지 글꼴 크기를 줄이기 위해 루프를 사용하여,이 페이지의 요구 이후 매우 느립니다 요소를 글꼴 크기를 변경 때마다 다시 렌더링합니다. 나는 결국 그것이 나 사용자 브라우저를 동결하지 않고 주기적으로 내용을 업데이트 할 수있는 방식으로 수행 할 수 있도록 내 자신의 알고리즘을 작성했다. 나는 당신이 그것을 얻을 수 있습니다 (패딩을 추가, 텍스트를 회전하는) 다른 기능을 추가하고 jQuery 플러그인으로 패키지 :

    다른 답변의 대부분은이 사업부에 맞을 때까지 글꼴 크기를 줄이기 위해 루프를 사용하여,이 페이지의 요구 이후 매우 느립니다 요소를 글꼴 크기를 변경 때마다 다시 렌더링합니다. 나는 결국 그것이 나 사용자 브라우저를 동결하지 않고 주기적으로 내용을 업데이트 할 수있는 방식으로 수행 할 수 있도록 내 자신의 알고리즘을 작성했다. 나는 당신이 그것을 얻을 수 있습니다 (패딩을 추가, 텍스트를 회전하는) 다른 기능을 추가하고 jQuery 플러그인으로 패키지 :

    https://github.com/DanielHoffmann/jquery-bigtext

    단순히 전화

    $("#text").bigText();
    

    그것은 당신의 용기에 잘 맞습니다.

    여기에 직접보기 :

    http://danielhoffmann.github.io/jquery-bigtext/

    그것은 몇 가지 제한 사항이 있습니다 지금은 사업부는 고정 된 높이와 너비를 가지고 있어야하며 여러 줄로 배치 텍스트를 지원하지 않습니다.

    나는 최대 글꼴 크기를 설정하는 옵션을 받고에서 작동합니다.

    편집 : 나는 플러그인 몇 가지 더 많은 문제를 발견, 그것은 표준 일 외에 다른 박스 모델을 처리하지 않고 사업부 마진이나 테두리를 가질 수 없습니다. 나는 그것을 작동합니다.

    EDIT2 : 지금 그 문제 및 제한 사항 및 추가 더 많은 옵션을 해결했습니다. 당신은 최대 글꼴 크기를 설정할 수 있습니다 당신은 또한 너비, 높이 또는 둘 중 하나를 사용하여 글꼴 크기를 제한 할 수 있습니다. I는 래퍼 요소의 최대 폭 및 최대 높이 값을 받아들이도록 작동한다.

    EDIT3 : 나는 버전 1.2.0로 플러그인을 업데이트했습니다. 스팬 태그 안에 내부 요소의 코드와 새로운 옵션 (은 verticalAlign,은 horizontalAlign, textAlign과) 및 지원에 관한 주요 정리 (행 구분 또는 글꼴 멋진 아이콘과 같은.)


  5. 5.이것은 GeekyMonkey 일부의 수정, 위의 게시 된 내용에 기초한다.

    이것은 GeekyMonkey 일부의 수정, 위의 게시 된 내용에 기초한다.

    ; (function($) {
    /**
    * Resize inner element to fit the outer element
    * @author Some modifications by Sandstrom
    * @author Code based on earlier works by Russ Painter (WebDesign@GeekyMonkey.com)
    * @version 0.2
    */
    $.fn.textfill = function(options) {
    
        options = jQuery.extend({
            maxFontSize: null,
            minFontSize: 8,
            step: 1
        }, options);
    
        return this.each(function() {
    
            var innerElements = $(this).children(':visible'),
                fontSize = options.maxFontSize || innerElements.css("font-size"), // use current font-size by default
                maxHeight = $(this).height(),
                maxWidth = $(this).width(),
                innerHeight,
                innerWidth;
    
            do {
    
                innerElements.css('font-size', fontSize);
    
                // use the combined height of all children, eg. multiple <p> elements.
                innerHeight = $.map(innerElements, function(e) {
                    return $(e).outerHeight();
                }).reduce(function(p, c) {
                    return p + c;
                }, 0);
    
                innerWidth = innerElements.outerWidth(); // assumes that all inner elements have the same width
                fontSize = fontSize - options.step;
    
            } while ((innerHeight > maxHeight || innerWidth > maxWidth) && fontSize > options.minFontSize);
    
        });
    
    };
    
    })(jQuery);
    

  6. 6.여기에서 사용 가능한 최대 크기를 찾기 위해 검색 진 것을 개선 방법의 반복 가능성이 적은 단계에서 상위에 맞는 (이것은보다 빠르고 정확하게 고정 된 폰트 크기로 스테핑 초과). 이 코드는 성능을 위해 여러 가지 방법으로 최적화되어 있습니다.

    여기에서 사용 가능한 최대 크기를 찾기 위해 검색 진 것을 개선 방법의 반복 가능성이 적은 단계에서 상위에 맞는 (이것은보다 빠르고 정확하게 고정 된 폰트 크기로 스테핑 초과). 이 코드는 성능을 위해 여러 가지 방법으로 최적화되어 있습니다.

    기본적으로, 10 이진 검색 단계는 최적의 크기의 0.1 %에서 얻을 수있는 것, 실행한다. 대신 최적의 크기의 2분의 1 ^ N에서 얻을 어떤 값 N에 numIter을 설정할 수 있습니다.

    CSS를 선택기로 전화, 예컨대 : fitToParent ( '제목 경간.');

    /**
     * Fit all elements matching a given CSS selector to their parent elements'
     * width and height, by adjusting the font-size attribute to be as large as
     * possible. Uses binary search.
     */
    var fitToParent = function(selector) {
        var numIter = 10;  // Number of binary search iterations
        var regexp = /\d+(\.\d+)?/;
        var fontSize = function(elem) {
            var match = elem.css('font-size').match(regexp);
            var size = match == null ? 16 : parseFloat(match[0]);
            return isNaN(size) ? 16 : size;
        }
        $(selector).each(function() {
            var elem = $(this);
            var parentWidth = elem.parent().width();
            var parentHeight = elem.parent().height();
            if (elem.width() > parentWidth || elem.height() > parentHeight) {
                var maxSize = fontSize(elem), minSize = 0.1;
                for (var i = 0; i < numIter; i++) {
                    var currSize = (minSize + maxSize) / 2;
                    elem.css('font-size', currSize);
                    if (elem.width() > parentWidth || elem.height() > parentHeight) {
                        maxSize = currSize;
                    } else {
                        minSize = currSize;
                    }
                }
                elem.css('font-size', minSize);
            }
        });
    };
    

  7. 7.크게 괴짜 원숭이의 대답이 아니라 jQuery를 의존하지 않고 영감 - 나는 AngularJS와에 대한 지침을 만들었습니다.

    크게 괴짜 원숭이의 대답이 아니라 jQuery를 의존하지 않고 영감 - 나는 AngularJS와에 대한 지침을 만들었습니다.

    데모 : http://plnkr.co/edit/8tPCZIjvO3VSApSeTtYr?p=preview

    마크 업

    지령

    app.directive('fittext', function() {
    
      return {
        scope: {
          minFontSize: '@',
          maxFontSize: '@',
          text: '='
        },
        restrict: 'C',
        transclude: true,
        template: '<div ng-transclude class="textContainer" ng-bind="text"></div>',
        controller: function($scope, $element, $attrs) {
          var fontSize = $scope.maxFontSize || 50;
          var minFontSize = $scope.minFontSize || 8;
    
          // text container
          var textContainer = $element[0].querySelector('.textContainer');
    
          angular.element(textContainer).css('word-wrap', 'break-word');
    
          // max dimensions for text container
          var maxHeight = $element[0].offsetHeight;
          var maxWidth = $element[0].offsetWidth;
    
          var textContainerHeight;
          var textContainerWidth;      
    
          var resizeText = function(){
            do {
              // set new font size and determine resulting dimensions
              textContainer.style.fontSize = fontSize + 'px';
              textContainerHeight = textContainer.offsetHeight;
              textContainerWidth = textContainer.offsetWidth;
    
              // shrink font size
              var ratioHeight = Math.floor(textContainerHeight / maxHeight);
              var ratioWidth = Math.floor(textContainerWidth / maxWidth);
              var shrinkFactor = ratioHeight > ratioWidth ? ratioHeight : ratioWidth;
              fontSize -= shrinkFactor;
    
            } while ((textContainerHeight > maxHeight || textContainerWidth > maxWidth) && fontSize > minFontSize);        
          };
    
          // watch for changes to text
          $scope.$watch('text', function(newText, oldText){
            if(newText === undefined) return;
    
            // text was deleted
            if(oldText !== undefined && newText.length < oldText.length){
              fontSize = $scope.maxFontSize;
            }
            resizeText();
          });
        }
      };
    });
    

  8. 8.나는 마커스 Ekwall에서 위의 스크립트를 포크 : https://gist.github.com/3945316 내 환경 설정에 쥐게, 지금 창 크기를 조정할 때, 그래서 그 아이가 항상 용기를 맞는 발생합니다. 내가 참조를 위해 아래의 스크립트를 붙여했습니다.

    나는 마커스 Ekwall에서 위의 스크립트를 포크 : https://gist.github.com/3945316 내 환경 설정에 쥐게, 지금 창 크기를 조정할 때, 그래서 그 아이가 항상 용기를 맞는 발생합니다. 내가 참조를 위해 아래의 스크립트를 붙여했습니다.

    (function($) {
        $.fn.textfill = function(maxFontSize) {
            maxFontSize = parseInt(maxFontSize, 10);
            return this.each(function(){
                var ourText = $("span", this);
                function resizefont(){
                    var parent = ourText.parent(),
                    maxHeight = parent.height(),
                    maxWidth = parent.width(),
                    fontSize = parseInt(ourText.css("fontSize"), 10),
                    multiplier = maxWidth/ourText.width(),
                    newSize = (fontSize*(multiplier));
                    ourText.css("fontSize", maxFontSize > 0 && newSize > maxFontSize ? maxFontSize : newSize );
                }
                $(window).resize(function(){
                    resizefont();
                });
                resizefont();
            });
        };
    })(jQuery);
    

  9. 9.여기에 영업 이익의 대답은 내 수정입니다.

    여기에 영업 이익의 대답은 내 수정입니다.

    즉,이를 최적화하기 위해 노력 많은 사람들이 루프가 사용되는 것을 불평했다. 루프가 느릴 수 있지만 예, 다른 접근 방법이 부정확 할 수 있습니다.

    따라서, 나의 접근 방식은 최적의 글꼴 크기를 찾기 위해 이진 검색 사용

    $.fn.textfill = function()
    {
        var self = $(this);
        var parent = self.parent();
    
        var attr = self.attr('max-font-size');
        var maxFontSize = parseInt(attr, 10);
        var unit = attr.replace(maxFontSize, "");
    
        var minFontSize = parseInt(self.attr('min-font-size').replace(unit, ""));
        var fontSize = (maxFontSize + minFontSize) / 2;
    
        var maxHeight = parent.height();
        var maxWidth = parent.width();
    
        var textHeight;
        var textWidth;
    
        do
        {
            self.css('font-size', fontSize + unit);
    
            textHeight = self.height();
            textWidth = self.width();
    
            if(textHeight > maxHeight || textWidth > maxWidth)
            {
                maxFontSize = fontSize;
                fontSize = Math.floor((fontSize + minFontSize) / 2);
            }
            else if(textHeight < maxHeight || textWidth < maxWidth)
            {
                minFontSize = fontSize;
                fontSize = Math.floor((fontSize + maxFontSize) / 2);
            }
            else
                break;
    
        }
        while(maxFontSize - minFontSize > 1 && maxFontSize > minFontSize);
    
        self.css('font-size', fontSize + unit);
    
        return this;
    }
    
    function resizeText()
    {
      $(".textfill").textfill();
    }
    
    $(document).ready(resizeText);
    $(window).resize(resizeText);
    

    이것은 또한 최소 및 최대 글꼴을 지정하는 요소를 할 수 있습니다 :

    <div class="container">
        <div class="textfill" min-font-size="10px" max-font-size="72px">
            Text that will fill the container, to the best of its abilities, and it will <i>never</i> have overflow.
        </div>
    </div>
    

    또한,이 알고리즘은 단위가없는 것이다. 당신은 등 REM %를, EM을 지정할 수 있으며, 그것의 최종 결과에 대한 것을 사용합니다.

    여기에 바이올린이있다 : https://jsfiddle.net/fkhqhnqe/1/


  10. 10.내 웹 사이트와 정확히 같은 문제가 있었다. 나는 벽, 큰 화면에 프로젝터에 표시되는 페이지가 ..

    내 웹 사이트와 정확히 같은 문제가 있었다. 나는 벽, 큰 화면에 프로젝터에 표시되는 페이지가 ..

    내 글꼴의 최대 크기를 모른다, 나는 @GeekMonkey의하지만, 글꼴 크기를 증가 위의 플러그인을 사용하는 재 :

    $.fn.textfill = function(options) {
            var defaults = { innerTag: 'span', padding: '10' };
            var Opts = jQuery.extend(defaults, options);
    
            return this.each(function() {
                var ourText = $(Opts.innerTag + ':visible:first', this);
                var fontSize = parseFloat(ourText.css('font-size'),10);
                var doNotTrepass = $(this).height()-2*Opts.padding ;
                var textHeight;
    
                do {
                    ourText.css('font-size', fontSize);
                    textHeight = ourText.height();
                    fontSize = fontSize + 2;
                } while (textHeight < doNotTrepass );
            });
        };
    

  11. 11.여기에 또한 minFontSize 매개 변수를 취할 수있는 허용 대답의 버전입니다.

    여기에 또한 minFontSize 매개 변수를 취할 수있는 허용 대답의 버전입니다.

    (function($) {
        /**
        * Resizes an inner element's font so that the inner element completely fills the outer element.
        * @author Russ Painter WebDesign@GeekyMonkey.com
        * @author Blake Robertson 
        * @version 0.2 -- Modified it so a min font parameter can be specified.
        *    
        * @param {Object} Options which are maxFontPixels (default=40), innerTag (default='span')
        * @return All outer elements processed
        * @example <div class='mybigdiv filltext'><span>My Text To Resize</span></div>
        */
        $.fn.textfill = function(options) {
            var defaults = {
                maxFontPixels: 40,
                minFontPixels: 10,
                innerTag: 'span'
            };
            var Opts = jQuery.extend(defaults, options);
            return this.each(function() {
                var fontSize = Opts.maxFontPixels;
                var ourText = $(Opts.innerTag + ':visible:first', this);
                var maxHeight = $(this).height();
                var maxWidth = $(this).width();
                var textHeight;
                var textWidth;
                do {
                    ourText.css('font-size', fontSize);
                    textHeight = ourText.height();
                    textWidth = ourText.width();
                    fontSize = fontSize - 1;
                } while ((textHeight > maxHeight || textWidth > maxWidth) && fontSize > Opts.minFontPixels);
            });
        };
    })(jQuery);
    

  12. 12.이 문제를 해결하기 위해 FitText.js (GitHub의 페이지)를 사용할 수 있습니다. 정말 작고 TextFill에 비해 효율적이다. TextFill 비싼 while 루프를 사용하고 FitText하지 않습니다.

    이 문제를 해결하기 위해 FitText.js (GitHub의 페이지)를 사용할 수 있습니다. 정말 작고 TextFill에 비해 효율적이다. TextFill 비싼 while 루프를 사용하고 FitText하지 않습니다.

    또한 맞춤 텍스트 (나는 아주 특별한 요구 사항과 챔피언 같은 작품과 프로젝트에서 사용!) 더 유연하다.

    HTML :

    <div class="container">
      <h1 id="responsive_headline">Your fancy title</h1>
    </div>
    
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
    <script src="jquery.fittext.js"></script>
    <script>
      jQuery("#responsive_headline").fitText();
    </script>
    

    당신은 또한에 대한 옵션을 설정할 수 있습니다 :

    <script>
      jQuery("#responsive_headline").fitText(1, { minFontSize: '30px', maxFontSize: '90px'});
    </script>
    

    CSS :

    #responsive_headline {
       width: 100%;
       display: block;
    }
    

    당신이 그것을 필요로하는 경우에 그리고, FitText 또한 노의 jQuery 버전이 있습니다.


  13. 13.편집 :이 코드는 HTML5 비디오의 상단에 메모를 표시하는 데 사용되었다. 동영상의 크기를 조정할 때 즉석에서 글꼴 크기를 변경 (브라우저 창 크기를 조정할 때.) 노트가있다 (유튜브에 노트와 같은) 비디오에 연결 한 이유 코드가 사용하는 인스턴스 대신 DOM 핸들 직접.

    편집 :이 코드는 HTML5 비디오의 상단에 메모를 표시하는 데 사용되었다. 동영상의 크기를 조정할 때 즉석에서 글꼴 크기를 변경 (브라우저 창 크기를 조정할 때.) 노트가있다 (유튜브에 노트와 같은) 비디오에 연결 한 이유 코드가 사용하는 인스턴스 대신 DOM 핸들 직접.

    요청에 따라 나는 이것을 달성하기 위해 사용하는 몇 가지 코드를 던질거야. (AN HTML5 비디오를 통해 텍스트 상자.) 코드는 오래 전에 쓰여진, 나는 솔직히 꽤 지저분한 것 같아요. 질문이 이미 대답하고 대답은 이미 오랜 시간이 인정되기 때문에 나는 이것을 다시 작성 귀찮게하지 않습니다 전. 누군가가 이것을 비트를 단순화하고자하는 경우, 당신은 환영보다 더있어!

    // Figure out the text size:
    var text = val['text'];
    var letters = text.length;
    var findMultiplier = function(x) { // g(x)
        /* By analysing some functions with regression, the resulting function that
         gives the best font size with respect to the number of letters and the size
         of the note is:
         g(x) = 8.3 - 2.75x^0.15 [1 < x < 255]
         f(x) = g(letters) * (x / 1000)^0.5
         Font size = f(size)
         */
        return 8.3 - 2.75 * Math.pow(x, 0.15);
    };
    
    var findFontSize = function(x) { // f(x)
        return findMultiplier(letters) * Math.pow(x / 1000, 0.5);
    };
    
    val.setFontSizeListener = function() {
        p.style.fontSize = '1px'; // So the text should not overflow the box when measuring.
        var noteStyle = window.getComputedStyle(table);
        var width = noteStyle.getPropertyValue('width');
        var height = noteStyle.getPropertyValue('height');
        var size = width.substring(0, width.length - 2) * height.substring(0, height.length - 2);
        p.style.fontSize = findFontSize(size) + 'px';
    };
    window.addEventListener('resize', val.setFontSizeListener);
    

    당신은 아마 글꼴 가족 글꼴 - 가족에서이 숫자를 조정할해야합니다. 이 작업을 수행하는 좋은 방법은 GeoGebra의라는 무료 그래프 시각화를 다운로드합니다. 텍스트의 길이와 상자의 크기를 변경합니다. 그럼 당신은 수동으로 크기를 설정합니다. 좌표 시스템에 수동 결과를 플롯. 그럼 당신은 내가 여기에 게시 한이 방정식을 입력하고 "내"그래프는 자신의 직접 그려 포인트를 맞을 때까지 당신은 숫자를 조정할.


  14. 14.제안 된 반복 솔루션은 두 개의 전선에서 극적으로 가속화 될 수있다 :

    제안 된 반복 솔루션은 두 개의 전선에서 극적으로 가속화 될 수있다 :

    1) 곱하기 폰트 일부 상수 크기보다는 추가 또는 1을 감산보다.

    2) 정수 과정을 사용하여 최초 제로는, 말하자면, 사이즈 각 루프 두배. 그런 다음, 시작하는 곳의 거친 아이디어, 곱셈 1.1, 미세한 조정, 말과 같은 일을한다. 완벽 주의자가 이상적인 글꼴의 정확한 정수 픽셀 크기를 할 수도 있지만, 대부분의 전문가들은 100 개 110 픽셀 사이의 차이를 통지하지 않습니다. 당신은 완벽 주의자 인 경우에, 더 미세한 조정으로 세 번째를 반복합니다.

    오히려 특정 루틴 또는 작성하는 것보다 그 정확한 질문에 대한 대답 플러그인, 난 그냥 레이아웃 문제의 모든 종류를 처리 할 수있는 코드의 기본 아이디어와 쓰기의 변화에 ​​의존뿐만 아니라 텍스트, 피팅 된 div, 스팬, 이미지를 포함한 ,. .. 폭, 높이, 면적, ... 컨테이너 내의 다른 요소와 일치 ....

    다음은 그 예이다 :

      var                           nWindowH_px             = jQuery(window).height();
      var                           nWas                    = 0;
      var                           nTry                    = 5;
    
      do{
       nWas = nTry;
       nTry *= 2;
       jQuery('#divTitle').css('font-size' ,nTry +'px');
      }while( jQuery('#divTitle').height() < nWindowH_px );
    
      nTry = nWas;
    
      do{
       nWas = nTry;
       nTry = Math.floor( nTry * 1.1 );
       jQuery('#divTitle').css('font-size' ,nTry +'px');
      }while( nWas != nTry   &&   jQuery('#divTitle').height() < nWindowH_px );
    
      jQuery('#divTitle').css('font-size' ,nWas +'px');
    

  15. 15.이것은 내가 만든 가장 우아한 솔루션입니다. 이 10 번 반복하고, 이진 검색을 사용합니다. 순진한 방법 while 루프을 오버 플로우 시작 소자까지 1 씩 폰트 크기를 증가하는 것이었다. 요소가 element.offsetHeight 및 element.scrollHeight를 사용하여 오버 플로우를 시작하면 확인할 수 있습니다. scrollHeight는 offsetHeight 값보다 큰 경우, 당신은 너무 큰 글꼴 크기를 가지고있다.

    이것은 내가 만든 가장 우아한 솔루션입니다. 이 10 번 반복하고, 이진 검색을 사용합니다. 순진한 방법 while 루프을 오버 플로우 시작 소자까지 1 씩 폰트 크기를 증가하는 것이었다. 요소가 element.offsetHeight 및 element.scrollHeight를 사용하여 오버 플로우를 시작하면 확인할 수 있습니다. scrollHeight는 offsetHeight 값보다 큰 경우, 당신은 너무 큰 글꼴 크기를 가지고있다.

    이진 검색이에 대한 더 나은 알고리즘이다. 또한 수행 할 반복 횟수에 의해 제한됩니다. 간단히 flexFont를 호출하고 DIV id를 삽입하고는 8px와 96px 사이의 글꼴 크기를 조정합니다.

    나는 약간의 시간이 주제를 연구하고 다른 라이브러리 노력을 보냈다, 그러나 궁극적으로 나는 이것이 가장 쉽고 간단한 해결책 것입니다 실제로 일이라고 생각합니다.

    참고 원하는 경우의 offsetWidth 및 scrollWidth을 사용하여 변경하거나이 기능을 모두 추가 할 수 있습니다.

    // Set the font size using overflow property and div height
    function flexFont(divId) {
        var content = document.getElementById(divId);
        content.style.fontSize = determineMaxFontSize(content, 8, 96, 10, 0) + "px";
    };
    
    // Use binary search to determine font size
    function determineMaxFontSize(content, min, max, iterations, lastSizeNotTooBig) {
        if (iterations === 0) {
            return lastSizeNotTooBig;
        }
        var obj = fontSizeTooBig(content, min, lastSizeNotTooBig);
    
        // if `min` too big {....min.....max.....}
        // search between (avg(min, lastSizeTooSmall)), min)
        // if `min` too small, search between (avg(min,max), max)
        // keep track of iterations, and the last font size that was not too big
        if (obj.tooBig) {
            (lastSizeTooSmall === -1) ?
                determineMaxFontSize(content, min / 2, min, iterations - 1, obj.lastSizeNotTooBig, lastSizeTooSmall) :
                    determineMaxFontSize(content, (min + lastSizeTooSmall) / 2, min, iterations - 1, obj.lastSizeNotTooBig, lastSizeTooSmall);
    
        } else {
            determineMaxFontSize(content, (min + max) / 2, max, iterations - 1, obj.lastSizeNotTooBig, min);
        }
    }
    
    // determine if fontSize is too big based on scrollHeight and offsetHeight, 
    // keep track of last value that did not overflow
    function fontSizeTooBig(content, fontSize, lastSizeNotTooBig) {
        content.style.fontSize = fontSize + "px";
        var tooBig = content.scrollHeight > content.offsetHeight;
        return {
            tooBig: tooBig,
            lastSizeNotTooBig: tooBig ? lastSizeNotTooBig : fontSize
        };
    }
    

  16. 16.저도 같은 문제가 생겼 및 솔루션은 기본적으로 컨트롤의 글꼴 크기에 자바 스크립트 사용된다. codepen에이 예제를 확인 :

    저도 같은 문제가 생겼 및 솔루션은 기본적으로 컨트롤의 글꼴 크기에 자바 스크립트 사용된다. codepen에이 예제를 확인 :

    https://codepen.io/ThePostModernPlatonic/pen/BZKzVR

    이 예는, 단지 높이 어쩌면 당신이 폭에 대한 몇 가지의 경우를 둘 필요가있다.

    <!doctype html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>Documento sem título</title>
    <style>
    </style>
    </head>
    <body>
    <div style="height:100vh;background-color: tomato;" id="wrap">        
      <h1 class="quote" id="quotee" style="padding-top: 56px">Because too much "light" doesn't <em>illuminate</em> our paths and warm us, it only blinds and burns us.</h1>
    </div>
    </body>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
    <script>
      var multiplexador = 3;
      initial_div_height = document.getElementById ("wrap").scrollHeight;
      setInterval(function(){ 
        var div = document.getElementById ("wrap");
        var frase = document.getElementById ("quotee");
        var message = "WIDTH div " + div.scrollWidth + "px. "+ frase.scrollWidth+"px. frase \n";
        message += "HEIGHT div " + initial_div_height + "px. "+ frase.scrollHeight+"px. frase \n";           
        if (frase.scrollHeight < initial_div_height - 30){
          multiplexador += 1;
          $("#quotee").css("font-size", multiplexador); 
        }
        console.log(message);          
      }, 10);
    </script>
    </html>
    

  17. 17.나는 좋아했다

    나는 좋아했다

    let name = "Making statements based on opinion; back them up with references or personal experience."
    let originFontSize = 15;
    let maxDisplayCharInLine = 50; 
    let fontSize = Math.min(originFontSize, originFontSize / (name.length / maxDisplayCharInLine));
    

  18. 18.그냥 contenteditables 내 버전을 추가하고 싶었다.

    그냥 contenteditables 내 버전을 추가하고 싶었다.

    $ .fn.fitInText = 함수 () { this.each (함수 () { 텍스트 상자 = $ (이)하자; textboxNode이 =하자; {mutationCallback = 함수 (mutationsList, 관찰자)하자 경우 (관찰자) { observer.disconnect (); } textbox.css ( '폰트 - 크기', 0); desiredHeight = textbox.css하자 ( '높이'); 대해 (ⅰ = 12; 나는 <50; I ++) { textbox.css ( '폰트 - 크기', I); 경우 (textbox.css ( '높이')> desiredHeight) { textbox.css ( '폰트 - 크기', I - 1); 단절; } } VAR의 구성 = { 속성 : 사실, childList : 사실, 하위 트리 : 사실, CharacterData를 : 사실 }; 하자 newobserver 새로운 MutationObserver (mutationCallback) =; newobserver.observe (textboxNode, 구성); }; mutationCallback (); }); } $ ( '# 내부') fitInText ().; #outer { 표시 : 테이블; 폭 : 100 %; } #inner { 국경 : 1 픽셀의 검은 색; 높이 : 170px; 텍스트 정렬 : 센터; 표시 : 테이블 셀; 수직 정렬 : 중간; 워드 브레이크 : 브레이크의 모든; } <스크립트 SRC = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js">

    테스트


  19. 19.나는 텍스트를 축소하는 루프의 사용을 방지 할 수있는 방법을 발견했다. 또한 컨테이너의 폭 및 폭의 함량 율을 곱함으로써 폰트 크기를 조정한다. 컨테이너의 폭이 내용의 1/3 그래서 만약, 글꼴 크기는 1/3 의지 컨테이너의 폭으로 감소 될 것입니다. 내용이 컨테이너보다 클 때까지 확장하기 위해, 나는, while 루프를 사용했다.

    나는 텍스트를 축소하는 루프의 사용을 방지 할 수있는 방법을 발견했다. 또한 컨테이너의 폭 및 폭의 함량 율을 곱함으로써 폰트 크기를 조정한다. 컨테이너의 폭이 내용의 1/3 그래서 만약, 글꼴 크기는 1/3 의지 컨테이너의 폭으로 감소 될 것입니다. 내용이 컨테이너보다 클 때까지 확장하기 위해, 나는, while 루프를 사용했다.

    function fitText(outputSelector){
        // max font size in pixels
        const maxFontSize = 50;
        // get the DOM output element by its selector
        let outputDiv = document.getElementById(outputSelector);
        // get element's width
        let width = outputDiv.clientWidth;
        // get content's width
        let contentWidth = outputDiv.scrollWidth;
        // get fontSize
        let fontSize = parseInt(window.getComputedStyle(outputDiv, null).getPropertyValue('font-size'),10);
        // if content's width is bigger than elements width - overflow
        if (contentWidth > width){
            fontSize = Math.ceil(fontSize * width/contentWidth,10);
            fontSize =  fontSize > maxFontSize  ? fontSize = maxFontSize  : fontSize - 1;
            outputDiv.style.fontSize = fontSize+'px';   
        }else{
            // content is smaller than width... let's resize in 1 px until it fits 
            while (contentWidth === width && fontSize < maxFontSize){
                fontSize = Math.ceil(fontSize) + 1;
                fontSize = fontSize > maxFontSize  ? fontSize = maxFontSize  : fontSize;
                outputDiv.style.fontSize = fontSize+'px';   
                // update widths
                width = outputDiv.clientWidth;
                contentWidth = outputDiv.scrollWidth;
                if (contentWidth > width){
                    outputDiv.style.fontSize = fontSize-1+'px'; 
                }
            }
        }
    }
    

    이 코드는 내가 Github에서 https://github.com/ricardobrg/fitText/에 업로드하는 테스트의 일부입니다


  20. 20.나는 geekMonkey 솔루션을 갔다,하지만 너무 느리다. 그가 무엇을하는지, 그 콘테이너 내의 맞는지 그 최대 폰트 크기 (maxFontPixels) 다음 수표를 조정한다. 그렇지 않으면 다시 검사하여 1 픽셀 및 폰트 크기를 감소시킨다. 이유는 단순히 높이에 대한 이전 컨테이너를 확인하고 그 값을 제출? (예, 그 높이 만에 작동하고 또한 최소 / 최대 옵션이 나는 이유를 알고,하지만 난 지금 해결책을 만든)

    나는 geekMonkey 솔루션을 갔다,하지만 너무 느리다. 그가 무엇을하는지, 그 콘테이너 내의 맞는지 그 최대 폰트 크기 (maxFontPixels) 다음 수표를 조정한다. 그렇지 않으면 다시 검사하여 1 픽셀 및 폰트 크기를 감소시킨다. 이유는 단순히 높이에 대한 이전 컨테이너를 확인하고 그 값을 제출? (예, 그 높이 만에 작동하고 또한 최소 / 최대 옵션이 나는 이유를 알고,하지만 난 지금 해결책을 만든)

    여기에 더 빨리 솔루션입니다 :

    var index_letters_resize;
    (index_letters_resize = function() {
      $(".textfill").each(function() {
        var
          $this = $(this),
          height = Math.min( Math.max( parseInt( $this.height() ), 40 ), 150 );
        $this.find(".size-adjust").css({
          fontSize: height
        });
      });
    }).call();
    
    $(window).on('resize', function() {
      index_letters_resize();
    );
    

    그리고 이것은 HTML과 같다 :

    <div class="textfill">
      <span class="size-adjust">adjusted element</span>
      other variable stuff that defines the container size
    </div>
    

    또이 용액을 용기의 높이 만 검사한다. 이 기능을 확인해야하지 않는 이유는 만약 요소 맞는 내부입니다. 그러나 나는 또한 최소 / 최대 값 (40 분, 150max) 그래서 나를 위해이 완벽하게 잘 작동 (또한 창 크기 조정에서 작동)을 구현했습니다.


  21. 21.다음은이 솔루션의 또 다른 버전입니다 :

    다음은이 솔루션의 또 다른 버전입니다 :

    shrinkTextInElement : function(el, minFontSizePx) {
        if(!minFontSizePx) {
            minFontSizePx = 5;
        }
        while(el.offsetWidth > el.parentNode.offsetWidth || el.offsetHeight > el.parentNode.offsetHeight) {
    
            var newFontSize = (parseInt(el.style.fontSize, 10) - 3);
            if(newFontSize <= minFontSizePx) {
                break;
            }
    
            el.style.fontSize = newFontSize + "px";
        }
    }
    
  22. from https://stackoverflow.com/questions/687998/auto-size-dynamic-text-to-fill-fixed-size-container by cc-by-sa and MIT license