2016-08-12 62 views
1

嘗試使用指令淡入點擊圖像。該指令在圖像第一次出現(初始頁面加載)時效果很好,可以很好地淡入淡出,但這不會發生在點擊上,它只是在沒有淡入淡出的情況下切換。我如何獲得指令fade-inng-click="onClick()"事件一起使用?使用指令點擊圖像時的角度褪色

我試着在directive$element.addClass("ng-hide-add");周圍加了一個超時時間,但沒有奏效。

Here's a plunkr

這裏的HTML:

<img ng-src="img/{{randTarotImg}}.jpg" class="tarot animate-show" ng-click="onClick()" fade-in/> 

這裏的JS:

angular.module('TarotApp') 
    .controller('TarotCtrl', function ($scope) { 

     $scope.tarotImg = []; 
      for (var i=1;i<=6;i++) { 
      $scope.tarotImg.push(i); 
     } 

     $scope.randTarotImg = $scope.tarotImg[Math.floor(Math.random() * $scope.tarotImg.length)]; 

     $scope.onClick = function() { 
       $scope.randTarotImg = $scope.tarotImg[Math.floor(Math.random() * $scope.tarotImg.length)]; 
     }; 

}) 

    .directive('fadeIn', function($timeout){ 
     return { 
      restrict: 'A', 
      link: function($scope, $element, attrs){ 
       $element.addClass("ng-hide-remove"); 
       $element.on('load', function() { 
        $element.addClass("ng-hide-add"); 
       }); 
      } 
     }; 
}); 

這裏的CSS:

.animate-show.ng-hide-add, .animate-show.ng-hide-remove { 
    transition: all linear 0.5s; 
    display: block !important; 
} 

.animate-show.ng-hide-add.ng-hide-add-active, .animate-show.ng-hide-remove { 
    opacity: 0; 
} 

.animate-show.ng-hide-add, .animate-show.ng-hide-remove.ng-hide-remove-active { 
    opacity: 1; 
} 
+0

您是否試圖在點擊時更改圖像,並且每次圖像加載時都想淡入? –

+0

@ravishankar是的,確切地說。我使用按鈕嘗試了這一點,但是我遇到了同樣的問題,指令沒有開火,(並且試圖讓按鈕完全看不見是一個挑戰):D,所以我用ng-click代替。 –

+0

添加和刪除類不會讓你得到結果,你需要保持它們之間的時間延遲。在添加'ng-hide-add'類之前用'setTimeOut()'試試 –

回答

2

在你的指令試試這個:

.directive('fadeIn', function($timeout){ 
    return { 
     restrict: 'A', 
     link: function($scope, $element, attrs){ 
      $element.addClass("ng-hide-remove"); 
      $element.on('load', function() { 
       $timeout($element.addClass("ng-hide-add"),1000);//Adding timeout 
      }); 
     } 
    }; 

希望這會有所幫助。

+0

謝謝,很好的嘗試,但不幸的是還沒有工作。我想知道爲什麼不是一個非常合乎邏輯的解決方案。 –

+0

再次感謝拉維,我最終得到了我的答案==> http://www.bennadel.com/blog/2497-cross-fading-images-with-angularjs.htm –

+0

謝謝你!你真的救了我的一天! – mark922