AngularJS动画
在angularJS中引入angular-animate.min.js库就可以使用动画效果,同时angularJS中也可以配合使用css.
- 什么是动画
动画就是通过操作HTML元素而引起动态变化的效果。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
div {
transition: all linear 1.5s;
background-color:blue;
height: 100px;
width: 50%;
position: static;
top: 0;
left: 0;
}
.ng-hide {
height: 100px;
width: 100px;
background-color:red;
top:-200px;
left: 200px;
}
</style>
<script src="https://cdn.staticfile.org/angular.js/1.4.6/angular.min.js"></script>
<script src="https://cdn.staticfile.org/angular.js/1.4.6/angular-animate.min.js"></script>
</head>
<body ng-app="ngAnimate">
<h1>点击观察: <input type="checkbox" ng-model="myCheck"></h1>
<div ng-hide="myCheck"></div>
</body>
</html>
其中style里是css样式,比如“transition: all linear 1.5s”,transition是一个效果过滤,具体“all”是运动样式,“linear”是运动类型,“1.5s”是运动;可以试试改变ng-hide里的样式看看效果。
如果已经设置了应用名,可以把 ngAnimate 直接添加在模型中,如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
div {
transition: all linear 1.5s;
background-color:blue;
height: 100px;
width: 50%;
position: static;
top: 0;
left: 0;
}
.ng-hide {
height: 100px;
width: 100px;
background-color:red;
top:-200px;
left: 200px;
}
</style>
<script src="https://cdn.staticfile.org/angular.js/1.4.6/angular.min.js"></script>
<script src="https://cdn.staticfile.org/angular.js/1.4.6/angular-animate.min.js"></script>
</head>
<body ng-app="myApp">
<h1>点击观察: <input type="checkbox" ng-model="myCheck"></h1>
<div ng-hide="myCheck"></div>
<script>
var app = angular.module('myApp', ['ngAnimate']);
</script>
</body>
</html>
- ngAnimate具体作用
ngAnimate本身并不能让HTML元素产生动画效果,但是它可以监听事件,类似于隐藏或者显示HTML元素。如果事件发生 ngAnimate 就会使用预定义的 class 来设置 HTML 元素的动画。
AngularJS 添加/移除 class 的指令:
- ng-show
- ng-hide
- ng-class
- ng-view
- ng-include
- ng-repeat
- ng-if
- ng-switch
ng-show和ng-hide上篇说过,是用来显示或者隐藏HTML元素的,其他指令会在进入 DOM 后添加 ng-enter 类,如果是移除 DOM 的话会添加 ng-leave 属性。
当 HTML 元素位置改变时,ng-repeat 指令同样可以添加 ng-move 类 。
在动画完成后,HTML 元素的类集合将被移除。例如: ng-hide 指令会添加以下类:
- ng-animate
- ng-hide-animate
- ng-hide-add (如果元素将被隐藏)
- ng-hide-remove (如果元素将显示)
- ng-hide-add-active (如果元素将隐藏)
- ng-hide-remove-active (如果元素将显示)
- 多种css
css的效果可以有多种,上面提到可以自己修改ng-hide的样式再看看效果,除此也可以试试平滑等效果,如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
@keyframes myCss{
from {
height: 50px;
} to {
height: 0px;
}
}
div {
height: 50px;
background-color: yellow;
}
div.ng-hide {
animation: 1.5s myCss;
}
</style>
<script src="https://cdn.staticfile.org/angular.js/1.4.6/angular.min.js"></script>
<script src="https://cdn.staticfile.org/angular.js/1.4.6/angular-animate.min.js"></script>
</head>
<body ng-app="ngAnimate">
<h1>点击观察: <input type="checkbox" ng-model="myCheck"></h1>
<div ng-hide="myCheck"></div>
</body>
</html>
注意一定要加ngAnimate!!