search
HomeWeb Front-endJS TutorialSummary of problems encountered when adding animation effects to angular_AngularJS

Adding "animation" is an effective way to let users perceive the behavior of the application. "List" is the most commonly used interface form in applications. There are often operations such as adding rows, deleting rows, and moving rows. Imagine that the adding operation is very simple. When deleting, it goes from large to small and then disappears; when adding, it goes from small to large; when moving, it means deleting first and then adding. It doesn't feel complicated, and it should be done by using CSS transition. However, in practice, we found that there are many problems to deal with. Let's go through them one by one.

Let’s do some simple tests

1. Initial version

<div class='list'>
  <div class='row-1'>row-1</div>
  <div class='row-2'>row-2</div>
</div>
.list{margin:20px;background:#eee;font-size:18px;color:white;}
.row-1{background:green;overflow:hidden;padding:15px;}
.row-2{background:blue;padding:15px;}
/*demo1*/
.demo-1 .remove{-webkit-transition: height 3s linear;}
.demo-1 .remove.active{height:0;}
var ele = document.querySelector('.demo-1 .row-1');
ele.classList.add('remove');
ele.classList.add('active');

The idea is very simple. By adding the "remove" class, set the effect of the animation, add "active" to modify the css attribute and activate the animation.

The result is different from what I expected. There are two problems: 1. The animation does not run; 2. row-1 does not disappear. Why? First of all, CSS transition cannot act on the auto attribute, because row-1 does not originally have a height set, so the animation from the existing height to 0 will not be generated. Second, height=0 only sets the content area to 0, and the padding has not changed, so row-1 still occupies 30px of space.

2. Specify a fixed height and add animation to padding

Adjust CSS

/*demo2*/
.demo-2 .row-1{height:48px;}
.demo-2 .remove{-webkit-transition: height 3s linear, padding-top 3s linear;}
.demo-2 .row-1.remove.active{height:0;padding-top:0;padding-bottom:0;}

The effect this time is correct, row-1 goes from 48px to 0, and the padding also changes accordingly.

3. Is there any other way? Do I have to specify height? Is transform okay?

Modify CSS

/*demo3*/
.demo-3 .remove{-webkit-transition: -webkit-transform 3s linear,padding 0s linear 3s;}
.demo-3 .row-1.remove.active{-webkit-transform-origin:0 0;-webkit-transform:scaleY(0);}


Even if the height is not set, there is no problem in performing animation through transform. The problem is that row-1 is still in its original place and still takes up space, and row-2 has not moved up. This brings about a problem. After the animation is executed (including the second example of setting height), row-1 is not deleted, but is invisible.

4. Solve the problem of clearing elements after animation execution

Modify CSS

Copy code The code is as follows:

.demo-4 .remove{-webkit-transition: height 3s linear, padding 3s linear, opacity 3s linear,color .5s linear;}
.demo-4 .row-1.remove.active{padding-top:0;padding-bottom:0;color:rgba(0,0,0,0);opacity:0;}

Modify JS

var ele, l;
ele = document.querySelector('.demo-4 .row-1');
l = ele.addEventListener('webkitTransitionEnd', function(evt){
  if (evt.propertyName === 'height') {
    ele.style.display = 'none';   
    ele.style.height = '';
    ele.removeEventListener('webkitTransitionEnd', l, false);
  }
}, false);
ele.style.height = ele.offsetHeight + 'px';
ele.classList.add('remove');
$timeout(function(){
  ele.classList.add('active');
  ele.style.height = '0px';
});

The effect this time is good. There are a few points to note: 1. By registering the transitionEnd event, you can capture the end of the animation; 2. You can execute multiple animations at the same time. A transitionEnd event will be generated at the end of each thing. You can know which property it is through the "propertyName" of the event. The animation is over.

5. I also tried using velocity.js

No need to set CSS
JS code

var ele = document.querySelector('.demo-5 .row-1');
Velocity(ele, 'slideUp', { duration: 1000 });

Looking at the execution process, I also modified the height and padding. However, velocity uses the requestAnimationFrame function. I think if the animation is relatively simple, there is no need to introduce other libraries, and the running effect of writing it directly will be almost the same.

6. Now that the height is clear, what about changing the width?

Adjust CSS

.demo-6 .row-1{width:100%;}
.demo-6 .remove{-webkit-transition: width 3s linear;}
.demo-6 .row-1.remove.active{width:0%;}

Although the width itself can be set by percentage, the problem of unfixed height still exists.

7. Use JS to solve the problem of changing width

Set CSS

.demo-7 .row-1{width:100%;height:48px;}
.demo-7 .remove{-webkit-transition: width 3s linear, opacity 3s ease;}
.demo-7 .row-1.remove.active{width:0%;opacity:0;}

固定了height已有动效正常了。其他的改进可参照前面的例子了。

二、一个完整的例子

完整的例子实在angular中实现的。angular实现首先一个问题就是在什么时机设置动效?因为,angular是双向绑定的,如果在controller中删除了一个对象,渲染界面的时候这个对象就没了,所以必须介入到数据绑定的过程中。angular提供ngAnimatie这个动画模块,试了一下它也确实可以完成ngRepeat列表数据更新的动效。但是要额外引入angular-animation.js,虽然不大,还是觉得不是很有必要。另外,我是在一个已经写好的框架页面上加动画,如果需要引入新的module,需要改框架文件,我觉得不好。试了试动态加载animation模块也没成功,所以就研究了一下自己怎么控制动效。

angular即使不加载animation模块,也有一个$animate,它为动效控制留出了接口。
看JS

var fnEnter = $animate.enter,
  fnLeave = $animate.leave;
$animate.enter = function() {
  var defer = $q.defer(),
    e = arguments[0],
    p = arguments[1],
    a = arguments[2],
    options = {
      addClass: 'ng-enter'
    };
  fnEnter.call($animate, e, p, a, options).then(function() {
    $animate.addClass(e, 'ng-enter-active').then(function(){
      var l = e[0].addEventListener('webkitTransitionEnd', function(){
        e[0].classList.remove('ng-enter-active');
        e[0].classList.remove('ng-enter');
        e[0].removeEventListener('webkitTransitionEnd', l, false);
        defer.resolve();
      }, false); 
    });
  });
  return defer.promise;
};
$animate.leave = function() {
  var defer = $q.defer(),
    e = arguments[0];
  $animate.addClass(e, 'ng-leave').then(function(){
    $animate.addClass(e, 'ng-leave-active').then(function(){
      var l = e[0].addEventListener('webkitTransitionEnd', function(){
        fnLeave.call($animate, e).then(function(){
          defer.resolve();
        });
      }, false);
    });
  });
  return defer.promise;
};

ng-repeat进行数据更新是会调用$animate服务的enters,leave和move方法,所以,要自己控制动效就要重写对应的方法。重写的时候要用$animate添加,直接在dom上设置有问题。(这一段的angular的逻辑比较底层,没有太看明白,还需要深入研究。)

另外,在移动行的位置时,要通过$timeout将删除和插入放到两个digest循环中处理,否则看不出效果。

var index = records.indexOf($scope.selected),
  r = records.splice(index, 1);
$timeout(function(){
  records.splice(index + 1, 0, r[0]);
},500);

angular的动画和digest循环关系密切,看了angular-animation.js的代码没看明白,还需要深入研究才行。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool