1

當某個文本添加到輸入字段並且文本超出其寬度時。現在,當焦點轉移到輸入字段之外(模糊)時,我想從開頭顯示文本(而不是用戶停止輸入的位置)。從文本長度大於文本框寬度的位置開始顯示文本

在Chrome中,它默認工作,即當輸入字段丟失焦點時,Chrome會自動將光標移動到文本的開頭。

在Mozilla,EDGE,IE這種行爲是行不通的。

回答

1

這很簡單。在Mozilla

var app = angular.module("sa", []); 
 

 
app.directive("fixCursorFoo", function() { 
 
    return { 
 
     restrict: 'A', 
 
     link: function ($scope, $element) { 
 
      $element.on("blur", function() { 
 
       var inp = $element[0]; 
 
       if (inp.createTextRange) { 
 
        var part = inp.createTextRange(); 
 
        part.move("character", 0); 
 
        part.select(); 
 
       } else if (inp.setSelectionRange) { 
 
        inp.setSelectionRange(0, 0); 
 
       } 
 
      }) 
 
     } 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 

 
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous"> 
 

 
<div ng-app="sa"> 
 
    <input type="text" fix-cursor-foo class="form-control" /> 
 
</div>

move cursor to the beginning of the input field?

運行此示例:創建一個指示,並從使用應答