avatar

目录
css-svg实现小于12号字体

效果

千山鸟飞绝 - 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 简洁)

文章作者: kshao
文章链接: https://blog.ksh7.com/2020/03/12/css-svg-12px-fontsize/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 kshao-blog
打赏
  • 微信
    微信
  • 支付寶
    支付寶