Calculate text width
by bc_rikko
HTML
<ul class="list">
<!--
<li class="item">
<p class="title -compress -ellipsis">あいうえお</p>
</li>
-->
</ul>
CSS
.list {
display: flex;
flex-wrap: wrap;
padding: 10px;
}
.list > .item {
margin: 10px;
}
.item {
width: 75px;
height: 30px;
box-shadow: 0 1px 3px rgba(0,0,0,.3);
background-color: white;
}
.item > .title {
overflow: hidden;
text-align: center;
line-height: 30px;
}
.title.-compress {
letter-spacing: -4px;
}
.title.-ellipsis {
white-space: nowrap;
text-overflow: ellipsis;
}
JavaScript
const list = document.getElementsByClassName('list')[0];
const generateTitle = i => {
const chars = ['あ', 'い', 'う', 'え', 'お'];
let title = '';
[...Array(i)].forEach((a, j) => title += chars[j % 5]);
return title;
};
// テキストの幅を取得
const getTextWidth = text => {
const span = document.createElement('span');
span.innerText = text;
span.style.visibility = 'hidden';
document.body.appendChild(span);
setTimeout(() => {
document.body.removeChild(span);
}, 100);
return span.offsetWidth || 0;
};
const main = () => {
[...Array(10)].forEach((a, i) => {
const item = document.createElement('li');
item.classList.add('item');
const title = document.createElement('p');
title.classList.add('title');
const text = generateTitle(i + 1);
const width = getTextWidth(text);
if (80 <= width && width <= 96) {
// 5〜6文字
title.classList.add('-compress');
} else if (96 < width) {
// 7文字以上
title.classList.add('-compress', '-ellipsis');
}
title.innerText = text;
item.appendChild(title);
list.appendChild(item);
});
};
main();