首页 > 解决方案 > 输入输入标签时如何使占位符逐个字符消失

问题描述

我有一个带有 6 点占位符角色的输入标签,如下所示:

在此处输入图像描述

如果我输入 9,根据刚刚输入的 9 所占据的位置,其中一个点会消失。

不像占位符属性的行为那样键入整个文本或设置为占位符的点一次消失。我又一次想让它一一消失。

理想情况下如下所示:

在此处输入图像描述

如果我输入数字并按退格键删除它,点肯定会回到原来的位置。

我找到了一个逐字符消失的占位符,但不幸的是,我必须使用输入标签,而不是像给定链接那样的 div 或 span。

我想知道有没有办法实现它。

提前致谢。

更新:

我最终在打字时让它消失了,但在删除用户输入时不太确定要带回这些点。

这是我在下面的尝试或对代码沙箱的简短复制: https ://codesandbox.io/s/verification-number-input-4f25l ?file=/src/VerificationNumberInput.tsx

// VerificationInput.tsx

const dotElement = <Dot
    width='11'
    height='11'
    viewBox='0 0 20 20'
    color='#e0e0e0'
  />;
  
  const [dots, setDots] = useState(Array(4).fill(dotElement));
  const [inputValue, setInputValue] = useState("");
  
  useEffect(() => {}, [dots]);

  const handleDots = (event: ChangeEvent<HTMLInputElement>) => {
      // remove dots when typing
      setInputValue(event.target.value);
      const copiedDots = [...dots];
      copiedDots.splice(0, 1);
      setDots(copiedDots);
   
      // logic to bring dots back again when userinput deleted
      // ???
  };

...

<div className='card-num__full'>
<input
  type='tel'
  autoComplete='on'
  maxLength={4}
  className='card-num__field'
  value={inputValue}
  onChange={handleDots}
  {...args}
/>

<div>
  {dots.map((d) => d)}
</div>
</div>
// css

.card-num__full {
  position: relative;
  width: 56px;
  height: 22px;
  display: flex;
  justify-content: flex-start;
  align-items: center;
}

input.card-num__field {
  position: absolute;
  top: 1px;
  width: 56px;
  height: 22px;
  display: flex;
  align-items: flex-start;
}

标签: javascriptcssreactjs

解决方案


推荐阅读