如何使用angularjs / HTML属性使文本框部分只读? 例如,具有默认值的文本框表示n#34; + 91",这是readonly,否则部分需要输入值。
答案 0 :(得分:7)
HTML
<input id="field" type="text" value="+91" size="50" />
<div id="output">
</div>
Javascript
var readOnlyLength = $('#field').val().length;
$('#output').text(readOnlyLength);
$('#field').on('keypress, keydown', function(event) {
var $field = $(this);
$('#output').text(event.which + '-' + this.selectionStart);
if ((event.which != 37 && (event.which != 39))
&& ((this.selectionStart < readOnlyLength)
|| ((this.selectionStart == readOnlyLength) && (event.which == 8)))) {
return false;
}
});
答案 1 :(得分:5)
基于Nitin上面的工作,我创建了这个角色指令,应该可以解决这个问题
的jsfiddle
http://jsfiddle.net/codemonkeytony/3ew5h6bf/7/
角
var partialApp = angular.module("partialApp", []);
partialApp.directive('partialReadonly', function () {
return {
restrict: 'A',
link: function (scope, elem, attrs) {
elem.on('keypress, keydown', function (event) {
var readOnlyLength = attrs["partialReadonly"].length;
if ((event.which != 37 && (event.which != 39))
&& ((elem[0].selectionStart < readOnlyLength)
|| ((elem[0].selectionStart == readOnlyLength) && (event.which == 8)))) {
event.preventDefault();
}
});
$(window).load(function () {
elem[0].value = attrs["partialReadonly"];
});
}
};
});
HTML
<input type="text" partial-readonly="Readonly text goes here" />
希望这有帮助
答案 2 :(得分:0)
..只因为你可以。这是另一种选择。
http://jsfiddle.net/davidcondrey/jhncLhL9/1/embedded/result/
textarea { display:inline-block;float:left;outline:0;margin:0;padding:0;resize:none; }
textarea:first-of-type { border:1px solid #000;border-right:0;}
textarea:last-of-type { border-left:0; }
<form>
<fieldset>
<textarea readonly="readonly" cols="2" rows="1">+91 changed</textarea>
<textarea class="var" cols="20" rows="1">Enter value here</textarea>
</fieldset>
</form>
或
http://jsfiddle.net/davidcondrey/955z0sc4/embedded/result/
input { text-indent:30px; }
input + span:before { position:absolute;color:#000; content:'91';left:35px;top:20px; }
<form>
<fieldset>
<input class="var"/><span></span>
</fieldset>
</form>