繁体   English   中英

基于容器大小的动态字体大小计算

[英]Dynamic font-size calculate based on container size

我的容器大小为 400wx300h。 容器内部是一个绑定到 Textarea 字段的单个段落标记。 最多可输入 255 个字符。段落标签的最大字体大小为 96 像素,最小为 28 像素。 现在,我想根据容器的高度计算段落的中间字体大小,以便它始终留在容器内而不会溢出。

这是我想出的一个简单的实现:

    import { useEffect, useRef, useState } from "react";

export default function App() {
  const [text, setText] = useState("");
  const [fontSize, setFontSize] = useState(96);
  const paragraph = useRef();

  useEffect(() => {
    let ph = paragraph.current.offsetHeight;
    let noOflines = ph / fontSize;
    let minFontsize = 28;
    let fs = 300 / noOflines;


    if (ph > 225) {
      console.log("fs and nolines and text length and ph", fs, noOflines, ph);
      if (fs < minFontsize) {
        setFontSize(minFontsize);
      } else {
        setFontSize(fs);
      }
    }
    if (fs > 96 && ph < 225 && noOflines <= 3) {
      console.log("fs and nolines and text length and ph", fs, noOflines, ph);
      setFontSize(96);
    }
  }, [text]);
  return (
    <div className="App" style={{ textAlign: "center" }}>
      <h1>Hello CodeSandbox</h1>
      <div
        style={{
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
          background: "red",
          width: "400px",
          margin: "auto",
          height: "300px"
        }}
      >
        <p
          id="par"
          style={{
            wordBreak: "break-word",
            lineHeight: 1,
            textAlign: "center",
            fontSize: fontSize
          }}
          ref={paragraph}
        >
          {text}
        </p>
      </div>
      <br />
      <br />
      <br />
      <textarea
        type="text"
        value={text}
        onChange={(e) => {
          if (e.target.value.length > 255) {
            return;
          }

          setText(e.target.value);
        }}
      />
    </div>
  );
}

https://codesandbox.io/s/clever-meadow-zooyo?file=/src/App.js:0-1644

它有效,但在某个地方存在我无法弄清楚的逻辑问题。 在某些情况下,段落溢出。 溢出段落

尝试以这种方式更改您的useEffect

useEffect(() => {
  let ph = paragraph.current.offsetHeight;

  if (ph > 300) {

    let noOflines = ph / fontSize;
    let minFontsize = 28;
    let fs = 300 / noOflines;

    setFontSize(fs < minFontsize ? minFontsize : fs);

  } else if (300 - fontSize > ph) {

    let noOflines = ph / fontSize;
    let fs = fontSize + fontSize / noOflines;

    setFontSize(fs > 96 ? 96 : fs);
  }
}, [text, fontSize]);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM