2014-09-29 146 views
5

如何使用angularjs/HTML屬性部分讀取文本框? 例如,默認值爲「+91」的文本框是隻讀的,否則部分需要輸入值。部分只讀文本框

+0

可能重複被編輯](http://stackoverflow.com/questions/15181417/how-to-make-only-some-text-in-a-text-box-read-o nly-while-allow-the-rest-to-be) – davidcondrey 2014-09-30 00:58:50

回答

6

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; 
    } 
});      

演示http://jsfiddle.net/Yt72H/

5

基於尼廷的工作上面,我創建這個角度指令應該做的伎倆

的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" /> 

希望這有助於

+0

http://plnkr.co/edit/oiJwq3295VkvyTGzlfsr?p=preview – PSL 2014-09-30 02:22:48

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> 
的[只讀如何讓只有在文本框中鍵入一些文字,同時允許其餘