There is a .text-wrap
block with a given size, there is an array of text strings in jQuery (of different lengths and padded). The task - when you click a button, enter random text into the block by adjusting its font size. There are no questions with random text, questions are precisely in adaptability =)
The first thing that came to mind:
In .text-wrap
add another div
with auto height and 100% width; it turns out so
<div class=".text-wrap"> <div class = ".text"> Тут текстовая строка </div> </div>
We add text with an obviously huge font size to the inner block and further reduce the font until the height of the inner one becomes less than the outer block.
Did through while
, function works. But for some texts she makes 300-400 passes. Especially if the font reduction step is small. then decided to reduce through recursion and multiplier. About 13-15 steps per two-line text are obtained.
Here is the code:
jQuery.noise = 15; //погрешность ресайза в пикс jQuery.step = 100; //шаг jQuery.startFontSize = 200; //стартовый размер шрифта jQuery.currentFontSize = 100; //текущий размер шрифта jQuery.stepCounter = 0; //счетчик действий jQuery.stepper = 1; //множитель шага шрифта (на это чилсо делим) function changeSizeDown(he1, block) //he1 - высота внешнего блока, block - блок с текстом { //если мы добились своего, заканчиваем рекурсию if(he1 - jQuery.noise < block.height() && block.height() < he1 + jQuery.noise) { //noise - погрешность высоты (т.к. 100% малый шанс попасть) return 1; } //иначе, если высота текста больше высоты блока else if(block.height() > he1) { jQuery.currentFontSize -= Math.ceil(jQuery.step/jQuery.stepper); console.log('Step: '+jQuery.stepCounter+' / Side: down / fsize: ' + jQuery.currentFontSize + ' / mult: x'+jQuery.stepper); console.log('Blocks: '+block.height()+' / ' + he1); block.css("font-size", jQuery.currentFontSize + "px"); changeSizeDown(he1, block); } //если высота блока меньше, то увеличиваем шрифт else if(block.height() < he1) { if(jQuery.stepper < 50) //если множитель шага < 50, то умножаем вдвое jQuery.stepper = jQuery.stepper*2; else //иначе мы уже подобрали максимально близкий размер шрифта, а шагов сделали слишком много. Поэтому стоп. return 0; jQuery.currentFontSize += Math.ceil(jQuery.step/jQuery.stepper); console.log('Step: '+jQuery.stepCounter+' / Side: up / fsize: ' + jQuery.currentFontSize + ' / mult: x'+jQuery.stepper); console.log('Blocks: '+block.height()+' / ' + he1); block.css("font-size", jQuery.currentFontSize + "px"); changeSizeDown(he1, block); } }
This code quickly copes with its task. But, like the cycle, it sometimes works incorrectly on mobile devices. Namely, it changes its size once, does not change it once.
Can anyone have ideas or simpler solutions? Googled a lot. I fitText
say that any fitText
is not suitable for me, since they only repel the width. And I have set the width and height.