Esta função ajusta o tamanho do texto de um elemento para que se ajuste ao tamanho do seu elemento pai, levando em consideração as opções de tamanho mínimo e máximo, bem como a capacidade de ter várias linhas de texto ou não.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
interface TextToFitOptions { | |
minSize?: number; | |
maxSize?: number; | |
multiLine?: boolean; | |
} | |
function textToFit(element: HTMLElement, options: TextToFitOptions = {}): void { | |
if (!(element instanceof HTMLElement)) { | |
console.error('O primeiro parâmetro deve ser um elemento HTML válido.'); | |
return; | |
} | |
// Obter o elemento pai | |
const parent = element.parentElement as HTMLElement; | |
// Obter as propriedades CSS do elemento pai | |
const parentStyle = getComputedStyle(parent); | |
const parentWidth = parent.offsetWidth; | |
const parentHeight = parent.offsetHeight; | |
const parentPadding = parseInt(parentStyle.padding); | |
// Definir o tamanho mínimo e máximo da fonte | |
const minSize = options.minSize ?? 10; | |
const maxSize = options.maxSize ?? 200; | |
// Definir se o texto pode ter várias linhas | |
const multiLine = options.multiLine ?? true; | |
element.style.whiteSpace = multiLine ? 'normal' : 'nowrap'; | |
// Iniciar o tamanho da fonte com o tamanho máximo | |
let fontSize = maxSize; | |
// Definir o tamanho do texto com base no tamanho do elemento pai | |
while (fontSize > minSize) { | |
element.style.fontSize = fontSize + "px"; | |
if ( | |
element.offsetWidth + parentPadding <= parentWidth && | |
element.offsetHeight + parentPadding <= parentHeight | |
) { | |
break; | |
} | |
fontSize--; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment