在加载时淡入图像

时间:2017-03-14 03:46:04

标签: javascript css angularjs

我有一个角度js指令,可以在加载图像时替换图像

.directive('imgOnLoad', function() {
  return {
    restrict: 'A',
    link: function(scope, element, attrs) {
      element.bind('load', function() {
        element[0].src = scope.obj.image_url;
      });
      element.bind('error', function(){
        console.log('failure!');
      });
    }
  };
})

我的图片标记

<img src="img/default.png" img-on-load>

这很好用,但是当我更换默认图像时我会添加淡入淡出效果。我认为如果我为ngAnimate引入 <ListView ItemsSource="{x:Bind ItemsSource, Mode=OneWay}" ItemTemplate="{x:Bind LineTemplate, Mode=OneWay}" SelectionMode="Multiple" > </ListView> 只是为了完成这项任务,那会有点过头了 - 可以通过角度或通过一些简单的CSS本地完成吗?

感谢任何帮助!

1 个答案:

答案 0 :(得分:1)

试用此代码

var demo = angular.module('demo', []);
demo.directive('imgOnLoad', function() {
  return {
    restrict: 'A',
    link: function(scope, element, attrs) {
      element.on('load', function() {
      if(scope.count==0){
      console.log("loaded "+(scope.count+1)+" time");
      setTimeout(function(){ 
      	$('#imgID').addClass('imgInitial');
      }, 1000);
      setTimeout(function(){ 
        element[0].src = "https://dummyimage.com/600x400/F7921E/fff";
      	$('#imgID').addClass('imgAnimate');
        $('#imgID').removeClass('imgInitial');
      }, 3000);
      scope.count=1;
      }
      });
    }
  };
});
.imgInitial {
    opacity: 0;
-webkit-transition: opacity 2s ease-out;
transition: opacity 2s ease-out;
}
.imgAnimate {
    opacity: 1;
    -webkit-transition: opacity 3s ease-in;
    transition: opacity 3s ease-in;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.2/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div ng-app='demo'>
    <div ng-init="count=0">
      <img id="imgID" src="https://dummyimage.com/600x400/000/fff" img-on-load>
    </div>
</div>