在運用angular開發移動端的應用時,發現它並沒有將ng-click做兼容,在移動端使用ng-click事件仍然會有300ms延遲。后來發現angular有一個專門針對移動端的模塊:angular-touch.js,其中對ng-click做了兼容性處理,以下為該模塊中部分內容:
/** * @ngdoc method * @name $touchProvider#ngClickOverrideEnabled * * @param {boolean=} enabled update the ngClickOverrideEnabled state if provided, otherwise just return the * current ngClickOverrideEnabled state * @returns {*} current value if used as getter or itself (chaining) if used as setter * * @kind function * * @description * Call this method to enable/disable {@link ngTouch.ngClick ngTouch's ngClick directive}. If enabled, * the default ngClick directive will be replaced by a version that eliminates the 300ms delay for * click events on browser for touch-devices. * * The default is `false`. * */ var ngClickOverrideEnabled = false; var ngClickDirectiveAdded = false; // eslint-disable-next-line no-invalid-this this.ngClickOverrideEnabled = function(enabled) { if (angular.isDefined(enabled)) { if (enabled && !ngClickDirectiveAdded) { ngClickDirectiveAdded = true; // Use this to identify the correct directive in the delegate ngTouchClickDirectiveFactory.$$moduleName = 'ngTouch'; $compileProvider.directive('ngClick', ngTouchClickDirectiveFactory); $provide.decorator('ngClickDirective', ['$delegate', function($delegate) { if (ngClickOverrideEnabled) { // drop the default ngClick directive $delegate.shift(); } else { // drop the ngTouch ngClick directive if the override has been re-disabled (because // we cannot de-register added directives) var i = $delegate.length - 1; while (i >= 0) { if ($delegate[i].$$moduleName === 'ngTouch') { $delegate.splice(i, 1); break; } i--; } } return $delegate; }]); } ngClickOverrideEnabled = enabled; return this; } return ngClickOverrideEnabled; };
其中說明引用該模塊,可以將ng-click替換為兼容移動端的點擊事件,具體代碼如下:
angular.module('myapp',['ngTouch'])
.config(['$touchProvider',function ($touchProvider) {
$touchProvider.ngClickOverrideEnabled(true);
}])
更新於2017.11.2
后來發現angular-touch模塊覆蓋原本的ng-click之后出現了點擊穿透的BUG,並且a標簽和button的點擊事件300ms延遲並沒有消失,后來還是選擇用fastclick.js好了,在angular中引入fastclick也非常簡單,並且使用fastclick之后,a標簽的點擊事件的延遲也消失了。
一共就兩行代碼:
<script src="./lib/fastclick.min.js"></script> //引入fastclick文件
myapp.config("xxxx",function(){
FastClick.attach(document.body);//在配置中加上這句話
})
