如何在输入字段中将占位符

如何在输入字段中将占位符

本文介绍了如何在输入字段中将占位符/输入文本居中,但保持光标向左对齐的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将占位符和键入的输入都放在输入字段的中心,但是当没有输入时,我希望光标保持左对齐.例如,如果我使用:

I want to center both the placeholder and the typed input in an input field, but when there is no input I want the cursor to remain left-aligned. For example, if I use:

input {
  text-align: center;
  width: 60px;
}

::placeholder {
  text-align: center;
}
<input type="text" placeholder="hello">

这将成功地将占位符和我输入的所有输入对齐到中心,但是会使光标在占位符的中心而不是向左闪烁

this will successfully align my placeholder and any input I type into the center, but makes the cursor flash in the center of the placeholder instead of to the left

我想将光标移动到输入中占位符"hello"中的h之前,但是当我键入任何输入时,功能应保持不变,即输入应居中.仅当没有输入时,光标才应保持对齐.

I would want to cursor to be before the h in "hello" which is the placeholder in the input, but when I type any input the functionality should remain the same, i.e. the input should be centered. The cursor should only be left aligned when there is no input.

推荐答案

您可以考虑 :占位符显示 .不需要JS

You can easily do this considering :placeholder-shown. No need for JS

input {
  text-align: center;
  width: 60px;
}

::placeholder {
  text-align: center;
}

input:placeholder-shown {
  text-align: left;
}
<input type="text" placeholder="hello">

这篇关于如何在输入字段中将占位符/输入文本居中,但保持光标向左对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 00:32