效果

千山鸟飞绝 - from hill to hill no bird in flight

千山鸟飞绝 - from hill to hill no bird in flight

html

<section class="s12-wrap">
<p style="font-size: 12px; margin: 0;padding-right: 10px;">
千山鸟飞绝 - from hill to hill no bird in flight
</p>
<svg id="size-svg" width="205.515625" height="14">
<text
id="size-text"
dominant-baseline="baseline"
font-size="12"
y="12"
style="line-height: 1; vertical-align: middle;"
>
千山鸟飞绝 - from hill to hill no bird in flight
</text>
</svg>
</section>

js

const svg = document.getElementById('size-svg');
const sText = document.getElementById('size-text');
const inp = document.getElementById('s12-inp');
let size = 12;
const fontsizeHeightMap = {
1: 1.22,
2: 2.52,
3: 3.63,
4: 5.02,
5: 6.03,
6: 7.52,
7: 8.52,
8: 9.14,
9: 10.52,
10: 11.52,
11: 13.02,
12: 14
};

const changeAttr = size => {
const value = fontsizeHeightMap[size];
svg.setAttribute('height', value);
if (size < 3) {
sText.setAttribute('y', value)
} else if (size === 3) {
sText.setAttribute('y', (value - 1).toFixed(2))
} else {
sText.setAttribute('y', (value - 2).toFixed(2))
}
sText.setAttribute('font-size', size)
inp.value = size;
}

inp.addEventListener('change', e => {
const num = e.target.value * 1
console.log(num);
if (num > 12) size = 12;
else if (num < 0) size = 1;
else size = num
changeAttr(size);
})

Tip
使用 svg 作为解决小于 12px 字号文字的方案:
使用 transform: scale() 设置后占位区域并没有改变,难以调节对齐方式。
使用 canvas 无法选中文字(也可以解决,但不如 svg 简洁)