Skip to content

Instantly share code, notes, and snippets.

@xogumon
Created March 5, 2023 16:35
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
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.
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