AngularJS animate image on src change

前端 未结 8 2193
一整个雨季
一整个雨季 2020-12-30 09:26

I have an AnuglarJS app, where I load/change some images from a webservice...

Controller

.controller(\'PlayerCtrl\', function($scope, programService         


        
8条回答
  •  情话喂你
    2020-12-30 10:12

    In case others end up here wanting to perform animations on change of a background image, I'll post what I ended up using.

    This directive assumes it's attached to a template like this:

    
    

    We want to set the background image source for the

    , but attach an onload event so we know when the new image has arrived. To do that, we use an with a .hidden class that has .hidden {display: none;}. Then we use the following directive to dynamically set the div's background image source and perform a fade to white then back from white on image change:

    /***
    *
    * Directive to dynamically set background images when 
    * controllers update their backgroundImageUrl scope
    * variables
    *
    * Template: 
    * AND * ***/ var angular = require('angular'); angular.module('BackgroundImage', []) .directive('backgroundImage', [ "$timeout", function ($timeout) { return function(scope, element, attrs){ attrs.$observe('backgroundImage', function(value) { /*** * * Define a callback to trigger once the image loads. * The value provided to this callback = the value * passed to attrs.$observe() above * ***/ var imageLoadedCallback = function(value) { // once the image load event triggers, remove the event // listener to ensure the event is called only once fadeOut(); target.removeEventListener('load', imageLoadedCallback); $timeout(function() { fadeIn(value); }, 700); } /*** * * Define fade in / out events to be called once a new image * is passed to the attrs.backgroundImage in the directive * ***/ var fadeOut = function() { element.css({'opacity': '0'}) }; var fadeIn = function(value) { element.css({ 'background': 'url(' + value +') no-repeat center center fixed', 'background-size' : 'cover', 'opacity': '1' }); }; // add an onload event to the hidden-full-screen-image var target = document.querySelector('.image-onload-target'); target.addEventListener('load', imageLoadedCallback(value)); }); }; }]);

    Working with Angular makes me love React all the more...

提交回复
热议问题