【问题标题】:String to Pixel using JavaScript : Static Content使用 JavaScript 将字符串转为像素:静态内容
【发布时间】:2023-01-31 16:24:57
【问题描述】:

静态内容

在单词的末尾放置一个字符。并且一旦用户键入,H 仍将保持关闭状态。

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>
        <div>
          <input
            type="text"
            value={val}
            onChange={(e) => setVal(e.target.value)}
          />
          <span>
            H
          </span>
        </div>
      </div>
    </div>
  );
}

【问题讨论】:

    标签: javascript


    【解决方案1】:

    这是解决方案: 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>
      );
    }
    

    【讨论】:

    • 现在这就是我要找的。令人惊讶的完成。太感谢了。你是摇滚明星。
    【解决方案2】:

    要为元素添加文本后缀,最简单的解决方案是在::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>

    【讨论】:

    • 哇。这是一个简单的答案。好的。
    猜你喜欢
    • 1970-01-01
    • 2012-03-14
    • 1970-01-01
    • 2019-04-14
    • 1970-01-01
    • 1970-01-01
    • 2014-05-18
    • 1970-01-01
    • 2014-09-05
    相关资源
    最近更新 更多