HTML中的可编辑单位<input type =“”number“”/>

时间:2015-03-31 12:19:57

标签: jquery html5 html-form html-input

我希望用户输入数字,例如“px”,“em”或“%”,然后使用箭头增加/减少值。

与此jQuery UI Spinner demo类似,但可以选择在输入字段内键入任何单位。

UPD: 我想出了适合我的solution

2 个答案:

答案 0 :(得分:1)

[Fiddle][solution]    
[solution]: http://jsfiddle.net/apurvaojas/yvLj1400/1/

$("input[type='number']").change(function(){
    var ip = $(this);
    switch($('select').val())
    {
			case 'per': $('div.block').width(ip.val()+"%"); 
			break;

			case 'em': $('div.block').width(ip.val()+"em");
			break;
            
            case 'px': $('div.block').width(ip.val()+"px");
			break;
			
			default: return; 
		}

});
div.block{
    background: red;
    width: 100px;
    height: 100px;
    margin-top:10px;
}
.container{
    width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="number" name="val">
    <select>
  <option value="per">%</option>
  <option value="em">em</option>
  <option value="px">px</option>
  
</select>
    <div class="container">
    <div class="block"></div>    
    </div>

我认为这可以解决您的问题。

答案 1 :(得分:0)

感谢N K的回答here。这是修改后的代码段,支持单位编辑。

$("#value").on("change", function(){
    var units = $("#units").val();
    console.log(units);
    $(".fake input").val(this.value + units);
});
$(".fake input").on("change", function(){
    var value = this.value.match(/(\d*\.?\d*)(.*)/);
    $("#value").val(value[1]);
    $("#units").val(value[2]);
});
.fake {
    position: relative;
    top: -20px;
    left: 2px;
    float: left;
}
.fake input {
    width: 145px;
    border: none;
    outline: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="original">
    <input id="value" type="number" step="1"/>
    <input id="units" type="hidden" name="units" value="px"/>
</div>
<div class="fake">
    <input type="text" value="0px"/>
</div>