标签:$scope ... 下标 utf-8 round break query input 使用
实现此功能的算法有很多,这里记录一个自己使用的:
<!DOCTYPE html> <html ng-app=‘myApp‘> <head> <meta charset=‘utf-8‘> <script src=‘angular.js‘></script> <script src=‘jquery-1.11.3.js‘></script> </head> <body> <div ng-controller=‘myCtrl‘> 字符串:<input ng-model="inputValue" ng-change=‘valueChangFnc(inputValue)‘ placeholder="请输入字符串"><br/> 字节限制显示:<input ng-model="maxByte" ng-change=‘byteChangFnc(maxByte)‘><br/> 处理结果:{{message}} </div> <script> angular.module("myApp",[]) .controller("myCtrl",function($scope){ $scope.inputValue = ""; $scope.maxByte = 10; $scope.valueChangFnc = function (inputValue){ if(inputValue) { $scope.message = getDisplayChars(inputValue, $scope.maxByte); } else { $scope.inputValue = ""; } } $scope.byteChangFnc = function (maxByte) { if(maxByte) { $scope.message = getDisplayChars(inputValue, $scope.maxByte); } else { $scope.maxByte = 10; } } function getDisplayChars(str, maxLength) { //计算字节数 var chars = 0; //存储超长时最后一位的下标 var sub = ‘‘; for (var i = 0; i < str.length; i++) { var code = str.charCodeAt(i); var char = code > 255 ? 2 : 1; chars += char; if (chars > maxLength) { sub = i; break; } } if (sub) { str = (str.slice(0, sub)) + ‘...‘ } return str; } }) </script> </body> </html>
标签:$scope ... 下标 utf-8 round break query input 使用
原文地址:http://www.cnblogs.com/guofan/p/7692660.html