typescript 使用JavaScript将字符串转换为像素:静态内容

jvlzgdj9  于 2022-12-30  发布在  TypeScript
关注(0)|答案(2)|浏览(145)
    • 静态内容**

要求是在用户输入某个值后放置H。但是,当输入超过1个单词时,H似乎太远。

    • 示例1:**使用一个单词:
    • 示例2:**具有多个单词

代码:https://codesandbox.io/s/infallible-fire-2qsmm5?file=/src/App.js

import "./styles.css";
import "bootstrap/dist/css/bootstrap.min.css";
import { useState } from "react";

export default function App() {
  const [val, setVal] = useState("Hello");
  return (
    <div className="App">
      <div className="input-group position-relative">
        <div className="form-floating">
          <input
            type="text"
            value={val}
            onChange={(e) => setVal(e.target.value)}
            className="form-control"
          />
          <span
            className=""
            style={{
              position: "absolute",
              top: "0.7rem",
              left: `${val?.length * 11}px`,
              color: "black",
              fontSize: "34px",
              fontWeight: "bold"
            }}
          >
            H
          </span>
        </div>
      </div>
    </div>
  );
}
xmjla07d

xmjla07d1#

解决方案如下:https://codesandbox.io/s/loving-orla-wfljwe?file=/src/App.js
灵感来源:Auto-scaling input to width of value in React

import "./styles.css";
import "bootstrap/dist/css/bootstrap.min.css";
import { useState, useRef, useEffect } from "react";

export default function App() {
  const [val, setVal] = useState("!Hello World ^_^");

  const [width, setWidth] = useState(0);
  const span = useRef();
  useEffect(() => {
    setWidth(span.current.offsetWidth);
  }, [val]);

  return (
    <div className="App">
      <div className="input-group position-relative">
        <div className="form-floating">
          <span
            ref={span}
            style={{
              position: "absolute",
              opacity: 0,
              zIndex: -1000,
              whiteSpace: "pre"
            }}
          >
            {val}
          </span>
          <input
            type="text"
            value={val}
            onChange={(e) => setVal(e.target.value)}
            className="form-control"
          />
          <span
            className=""
            style={{
              position: "absolute",
              top: "0.7rem",
              left: `${width + 16}px`,
              color: "red",
              fontSize: "34px",
              fontWeight: "bold"
            }}
          >
            {val.substring(0, 1).toUpperCase()}
          </span>
        </div>
      </div>
    </div>
  );
}
jhiyze9q

jhiyze9q2#

要给元素添加文本后缀,最简单的解决方案是在::after pseudo-element上使用CSS content(而不是编写复杂的JS计算):

.example {
  display: inline-flex;
  align-items: center;
}

.example::after {
  content: "H";
  font-size: 2rem;
  font-weight: 900;
  /* add margin-left if needed */
}
<span class="example">Hello</span>
<br>
<span class="example">Hello Why Are You So Close</span>

相关问题