使输入数字字段的最右边部分不可编辑

时间:2017-05-02 09:17:51

标签: javascript jquery html css html5

我想要这样的事情:

enter image description here

此处%符号默认位于输入字段中,无法编辑或删除。用户只能编辑%符号左侧的数字。按下向上或向下箭头时,只有%符号左侧的数字会增加或减少。

例如,如果我现在按向上箭头,它将显示

  

11%

,如果我按下箭头,它将显示

  

9%

我已经看到一些例子,用于保持输入字段的最左边部分不可编辑,但在这里我需要最右边的部分是不可编辑的。

3 个答案:

答案 0 :(得分:3)

请查看此JSfiddle。我想这会对你有帮助。

<input id="edit_input" type="number"  style="width:80px;"></input>
<p>%</p>

input {
  float:left;
  font-size: 16px;
  padding: 0px 0 0px 0px;
  box-sizing:border-box;
}
p {
 margin:-4px 0px 0px -50px;
float:left;
padding-top: 5px;
cursor: default;
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
 font-size: 20px;
}

答案 1 :(得分:1)

    .edit-wrapper {
  max-width: 200px;
  position: relative;
}

.edit-wrapper input[type=number] {
  width: 100%;
  text-align: right;
  box-sizing: border-box;
}

input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
  margin-left: 20px;
}

.edit-wrapper:before {
    content: '%';
    position: absolute;
    right: 20px;
    top: 1px;
}
<div class="edit-wrapper">
<input id="edit_input" type="number">
</div>

答案 2 :(得分:0)

只需在keyup上通过JavaScript添加后缀。

$('input[data-suffix]').on('keyup.addsuffix', function(e) {
  
  var suffix = $(this).data('suffix'),
      inputValue = $(this).val().replace(suffix, '');
      
  $(this).val(inputValue + suffix);
  
}).trigger('keyup.addsuffix');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value="3" data-suffix="%">

我知道并不那么酷。如何将后缀与输入分开,就像在Bootstrap中一样?我认为会更强大。