【问题标题】:Is there a way to adjust the font-size to fit a fixed box without using css overflow? [duplicate]有没有办法在不使用 css 溢出的情况下调整字体大小以适应固定框? [复制]
【发布时间】:2022-01-11 04:37:59
【问题描述】:

<div style="width : 50px"></div>

当字母数量增加并离开该区域时, 有没有办法自动减小字体大小而不是 css 溢出?

【问题讨论】:

标签: javascript html css


【解决方案1】:

我发现这个问题很有趣,所以我将提供一个简单的 JavaScript 示例,以防它对某人有所帮助。

const div = document.querySelector('div');
const span = document.querySelector('span');


createDynamicTextbox(div, span);


function createDynamicTextbox(outer, inner) {
  if (!outer.style.fontSize) outer.style.fontSize = outer.clientHeight;
  const initialSize = +outer.style.fontSize.match(/\d+/)[0];

  inner.addEventListener('input', function(e) {
    let [n, unit] = outer.style.fontSize.split(/(?<![a-z])(?=[a-z]+)/);
    n=+n;

    while (outer.offsetWidth > inner.offsetWidth) {
      n++;
      outer.style.fontSize = n+unit;
      if (n >= initialSize) return;
    }

    while (inner.offsetWidth > outer.offsetWidth) {
      n--;
      outer.style.fontSize = n+unit;
      if (n <= 0) return;
    }
  });

  inner.dispatchEvent(new InputEvent('input'));
}
div {
  width: 100px;
  overflow: hidden;
  white-space: nowrap;
}
&lt;div style="font-size: 30px"&gt;&lt;span contenteditable&gt;Edit Me&lt;/span&gt;&lt;/div&gt;

【讨论】:

    猜你喜欢
    • 2017-07-29
    • 2019-09-26
    • 2018-04-28
    • 2015-07-10
    • 2021-12-20
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多