algo de debordement adapatif des très longs titres sur images

This commit is contained in:
2026-09-15 16:27:20 +02:00
parent e6adf29505
commit af7d4192e6
4 changed files with 60 additions and 2 deletions
@@ -45,6 +45,56 @@ function initTitles() {
hyphenateWord(chars);
}
txt.classList.add("is-ready");
measureOverflow(txt);
}
}
/**
* Mesure le débordement du titre sous l'image et pose data-overflow-lines.
*
* Si le titre déborde de N lignes sous l'image, l'attribut data-overflow-lines
* permet au CSS d'augmenter max-height de N lignes pour absorber le débordement.
*/
function measureOverflow(h2) {
const article = h2.closest('article.has-image');
if (!article) return;
const img = article.querySelector('header .field_images img');
if (!img) return;
const measure = () => {
const lineHeight = parseFloat(getComputedStyle(h2).lineHeight);
if (!lineHeight) return;
// Hauteur réelle de l'image rendue (width:100%, height:auto).
let imgHeight;
if (img.naturalWidth && img.complete) {
imgHeight = img.clientWidth * (img.naturalHeight / img.naturalWidth);
} else {
imgHeight = img.clientHeight;
}
if (!imgHeight) return;
// scrollHeight = hauteur totale du titre sans le max-height.
h2.style.maxHeight = 'none';
const titleHeight = h2.scrollHeight;
h2.style.maxHeight = '';
// Lignes du titre qui dépassent sous l'image.
// 1 ligne est déjà dans le flux (max-height: 1em par défaut).
const overflowPx = titleHeight - imgHeight;
if (overflowPx <= 0) return;
const overflowLines = Math.ceil(overflowPx / lineHeight);
if (overflowLines > 0) {
h2.setAttribute('data-overflow-lines', overflowLines);
}
};
if (img.complete && img.naturalWidth) {
measure();
} else {
img.addEventListener('load', measure, { once: true });
}
}