Я пытаюсь сжать однострочную строку текста в текстовом поле / области.Смотрите пример ниже.Кредит Уменьшение размера шрифта для пользовательских типов, чтобы соответствовать вводу, используя Javascript для написания кода.
http://jsfiddle.net/hsdntz7y/4/
// txt is the text to measure, font is the full CSS font declaration,
// e.g. "bold 12px Verdana"
function measureText(txt, font) {
var id = 'text-width-tester',
$tag = $('#' + id);
if (!$tag.length) {
$tag = $('<span id="' + id + '" style="display:none;font:' + font + ';">' + txt + '</span>');
$('body').append($tag);
} else {
$tag.css({
font: font
}).html(txt);
}
return {
width: $tag.width(),
height: $tag.height()
}
}
function shrinkToFill(input, fontSize, fontWeight, fontFamily) {
var $input = $(input),
txt = $input.val(),
maxWidth = $input.width(),
font = fontWeight + " " + fontSize + "px " + fontFamily;
// see how big the text is at the default size
var textWidth = measureText(txt, font).width + measureText(txt, font).width * .1; //padding to try to prevent cutoff letters?
if (textWidth > maxWidth) {
// if it's too big, calculate a new font size
// the extra .9 here makes up for some over-measures
fontSize = fontSize * maxWidth / textWidth * .9;
font = fontWeight + " " + fontSize + "px " + fontFamily;
// and set the style on the input
$input.css({
font: font
});
} else {
// in case the font size has been set small and
// the text was then deleted
$input.css({
font: font
});
}
}
$(function() {
$('#my_input').keyup(function() {
shrinkToFill(this, 100, "", "Georgia, serif");
})
});
input {
font: 100px Georgia, serif;
width: 80%;
height: 300px;
line-height: 30px;
text-align: center;
position: absolute;
border-width: 0;
margin-right: 5%;
margin-left: 5%;
top: 25%;
}
*:focus {
outline: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="my_input" value="Type Here">
Мои проблемы:
- Когда я набираю пробелы между словами и добавляю больше слов, строковый шрифт нене сжимается, чтобы поместиться в поле.
- Как я могу установить максимальный / минимальный размер шрифта, при котором он перестает сжиматься / расширяться?
- Я хотел бы сделать текстовую область / поле и усадку/ расширение размера шрифта текста для динамической регулировки при изменении размера окна.
- Я хочу убедиться, что в начале и в конце строки отсутствуют обрезанные буквы.Смотрите картинку.
Любая помощь будет принята с благодарностью.Я искал и работал над этим часами и подумал, что кто-то более знающий, чем я, мог бы показать мне через несколько минут.
Спасибо за ваше время.