将文本后缀添加到< input type =“数字">中. [英] Add a text suffix to <input type="number">

查看:393
本文介绍了将文本后缀添加到< input type =“数字">中.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有很多这样的输入:

I currently have a number of inputs like this:

<input type="number" id="milliseconds">

此输入字段用于表示以毫秒为单位的值. 但是,我确实有多个数字输入,这些输入采用dB或百分比形式的值.

This input field is used to represent a value in milliseconds. I do however have multiple number inputs which take a value in dB or percentages.

<input type="number" id="decibel">
<input type="number" id="percentages">

我想做的是在输入字段中添加类型后缀,以使用户知道输入代表哪种类型的值.像这样:

What I would like to do is add a type suffix to the input field to let users know what kind of value the input represents. Something like this:

(编辑此图像以显示我想要的结果,我也隐藏了输入类型的向上和向下箭头).

(This image is edited to show what result I want to have,I hid the up and down arrows from the input type as well).

我已经尝试过对此进行搜索,但似乎找不到任何相关信息.有谁知道这是否可行,以及您如何实现这样的目标?

I have tried to Google this but I can't seem to find anything about it. Does anyone know if this is possible, and how you can accomplish something like this?

推荐答案

您可以为每个输入元素使用包装器<div>,并将该单元定位为伪元素

You can use a wrapper <div> for each input element and position the unit as a pseudo element ::after with the content of your corresponding units.

对于绝对定位的伪元素,此方法效果很好,不会影响现有布局.不过,这种方法的缺点是,必须确保用户输入的内容与文本字段的长度不符,否则该单元将在上面令人讨厌地显示.对于固定的用户输入长度,应该可以正常工作.

This approach works well for the absolute positioned pseudo elements will not effect the existing layouts. Nevertheless, the downside of this approach is, that you have to make sure, that the user input is not as long as the text field, otherwise the unit will be unpleasantly shown above. For a fixed user input length, it should work fine.

/* prepare wrapper element */
div {
  display: inline-block;
  position: relative;
}

/* position the unit to the right of the wrapper */
div::after {
  position: absolute;
  top: 2px;
  right: .5em;
  transition: all .05s ease-in-out;
}

/* move unit more to the left on hover or focus within
   for arrow buttons will appear to the right of number inputs */
div:hover::after,
div:focus-within::after {
  right: 1.5em;
}

/* handle Firefox (arrows always shown) */
@supports (-moz-appearance:none) {
  div::after {
    right: 1.5em;
  }
}

/* set the unit abbreviation for each unit class */
.ms::after {
  content: 'ms';
}
.db::after {
  content: 'db';
}
.percent::after {
  content: '%';
}

<div class="ms">
  <input type="number" id="milliseconds" />
</div>
<hr />
<div class="db">
  <input type="number" id="decibel" />
</div>
<hr />
<div class="percent">
  <input type="number" id="percentages">
</div>

如果您要支持浏览器,而根本不显示这些箭头,请使用 media查询.

If you want to support browsers, that doesn't show these arrows at all, make use of @supports or media queries.

这篇关于将文本后缀添加到&lt; input type =“数字"&gt;中.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆