如何在输入元素(或其外部)内部添加浮动到"lbs"之类的基于文本的单元?

dko*_*oss 7 html css twitter-bootstrap

是否可以在输入元素中插入单位?<input>元素内部是首选,但外部是可以接受的.

在此输入图像描述

pol*_*ata 14

你可以使用这样的东西

<input></input><span style="margin-left:10px;">lb</span>
Run Code Online (Sandbox Code Playgroud)

Inisde

<input style="padding-right:20px; text-align:right;" value="50"></input><span style="margin-left:-20px;">lb</span>
Run Code Online (Sandbox Code Playgroud)

小提琴


Mwi*_*iza 7

您可以使用引导输入组组件。

注意:下面的示例使用 bootstrap 4 类

<div class="input-group">
   <input type="number" class="form-control">
   <div class="input-group-append">
       <span class="input-group-text"> m </span>
   </div>
</div>
Run Code Online (Sandbox Code Playgroud)

结果如下:

在此处输入图片说明


cca*_*dar 6

如果您希望单位显示在数字旁边,您可以尝试这个技巧(https://jsfiddle.net/ccallendar/5f8wzc3t/24/)。输入值呈现在位于输入顶部的 div 中,并隐藏值部分。这样单元就可以正确定位。只需确保使用相同的样式(字体大小、颜色、填充等)。

输入单位

const input = document.getElementById("input");
const hiddenValue = document.getElementById("hiddenValue");
const unitsValue = document.getElementById("unitsValue");
input.addEventListener("input", () => {
  hiddenValue.innerHTML = input.value;
  // Only show units when there is a value?
  // unitsValue.innerHTML = (input.value.length > 0 ? " km" : "");
});
Run Code Online (Sandbox Code Playgroud)
.wrapper {
  position: relative;
  width: 80px;
}

#input {
  border: 2px solid #fee400;
  background-color: #373637;
  width: 100%;
  font-family: serif;
  font-size: 18px;
  line-height: 25px;
  font-weight: normal;
  padding: 3px 3px 3px 10px;
  color: white;
}

.units {
  position: absolute;
  top: 0;
  left: 0;
  right: 10px;
  bottom: 0;
  pointer-events: none;
  overflow: hidden;
  display: flex;
  
  /* Match input styles */
  font-family: serif;
  font-size: 18px;
  line-height: 25px;
  font-weight: normal;
  
  /* includes border width */
  padding: 5px 5px 5px 12px;
  color: white;
  opacity: 0.8;
}

.invisible {
  visibility: hidden;
}

#unitsValue {
  /* Support spaces */
  white-space: pre;
}
Run Code Online (Sandbox Code Playgroud)
<div class="wrapper">
  <input id="input"type="number" value="12" />
  <div class="units">
    <span class="invisible" id="hiddenValue">12</span>
    <span class="units-value" id="unitsValue"> km</span>
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)


Oli*_*der 5

position: relative我将通过使用和在输入上轻推一个额外的元素(如跨度)来做到这一点left: -20px

然后padding-right在输入元素上进行一些操作,以确保用户的输入不会与新元素重叠。

这里的例子:

https://jsfiddle.net/peg3mdsg/1/