2016-08-12 66 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