search
HomeWeb Front-endHTML Tutorial给angular的repeat列表的行操作加上动效遇到的问题总结_html/css_WEB-ITnose

加入“动效”是让用户对应用的行为进行感知的一种有效手段。“列表”是应用中最常使用的一种界面形式,经常会有添加行,删除行,移动行这些操作。设想添加的操作很简单,删除时从大到小,然后消失;添加时从小到大;移动就是先删除再添加。感觉上并不复杂,应该利用CSS的transition就能搞定,可是实际做起来发现有不少问题要处理,下面一一道来。

来些简单的测试

1、最初的版本

<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');

想法很简单,通过添加“remove”类,设置动画的效果,添加“active”修改css属性,激活动画。

结果和想的不一样,两个问题:1、动画并没有运行;2、row-1并没有消失。为什么?首先,CSS的transition不能作用于auto的属性,因为row-1本来并没有设置height,所以不会产生从现有的高度变到0的动画。第二,height=0只是设置了content区域为0,padding并没有改变,所以还是row-1还是占据了30px的空间。

2、指定固定的height并且padding也加上动画

调整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;}

这次的效果是对的,row-1从48px边到0,同时padding也跟着变。

3、还有没有别的办法呢?一定要指定height吗?transform行不行

修改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);}

即使没有设置height,通过transform执行动画也是没有问题的。问题是,row-1还在原来的地方,还占着空间,row-2并没有向上挪。由此带来个问题,动画执行完了(包括第2个设置height的例子),row-1并没有删除掉,只是看不见了。

4、解决动画执行完清除元素的问题

修改CSS

.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;}

修改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';});

这次的效果不错。有几个注意的地方:1、通过注册transitionEnd事件可以捕获到动结束;2、可以同时执行多个动效,每个东西结束都会产生transitionEnd事件,通过事件的“propertyName”可以知道是哪个属性的动效结束了。

5、用velocity.js也试了一下

CSS不用设置JS代码

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

看了看执行的过程,也是修改height和padding。但是,velocity用的是requestAnimationFrame函数。我认为如果动效比较简单,就不用引入其他的库了,直接写出来的运行效果差不多。

6、高度搞明白了,变宽度呢?

调整CSS

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

虽然宽本身可以通过百分比进行设置,但是height不固定的问题还是存在。

7、用上JS解决变width的问题

设置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
Difficulty in updating caching of official account web pages: How to avoid the old cache affecting the user experience after version update?Difficulty in updating caching of official account web pages: How to avoid the old cache affecting the user experience after version update?Mar 04, 2025 pm 12:32 PM

The official account web page update cache, this thing is simple and simple, and it is complicated enough to drink a pot of it. You worked hard to update the official account article, but the user still opened the old version. Who can bear the taste? In this article, let’s take a look at the twists and turns behind this and how to solve this problem gracefully. After reading it, you can easily deal with various caching problems, allowing your users to always experience the freshest content. Let’s talk about the basics first. To put it bluntly, in order to improve access speed, the browser or server stores some static resources (such as pictures, CSS, JS) or page content. Next time you access it, you can directly retrieve it from the cache without having to download it again, and it is naturally fast. But this thing is also a double-edged sword. The new version is online,

How do I use HTML5 form validation attributes to validate user input?How do I use HTML5 form validation attributes to validate user input?Mar 17, 2025 pm 12:27 PM

The article discusses using HTML5 form validation attributes like required, pattern, min, max, and length limits to validate user input directly in the browser.

What are the best practices for cross-browser compatibility in HTML5?What are the best practices for cross-browser compatibility in HTML5?Mar 17, 2025 pm 12:20 PM

Article discusses best practices for ensuring HTML5 cross-browser compatibility, focusing on feature detection, progressive enhancement, and testing methods.

How to efficiently add stroke effects to PNG images on web pages?How to efficiently add stroke effects to PNG images on web pages?Mar 04, 2025 pm 02:39 PM

This article demonstrates efficient PNG border addition to webpages using CSS. It argues that CSS offers superior performance compared to JavaScript or libraries, detailing how to adjust border width, style, and color for subtle or prominent effect

What is the purpose of the <datalist> element?What is the purpose of the <datalist> element?Mar 21, 2025 pm 12:33 PM

The article discusses the HTML <datalist> element, which enhances forms by providing autocomplete suggestions, improving user experience and reducing errors.Character count: 159

What is the purpose of the <meter> element?What is the purpose of the <meter> element?Mar 21, 2025 pm 12:35 PM

The article discusses the HTML <meter> element, used for displaying scalar or fractional values within a range, and its common applications in web development. It differentiates <meter> from <progress> and ex

How do I use the HTML5 <time> element to represent dates and times semantically?How do I use the HTML5 <time> element to represent dates and times semantically?Mar 12, 2025 pm 04:05 PM

This article explains the HTML5 <time> element for semantic date/time representation. It emphasizes the importance of the datetime attribute for machine readability (ISO 8601 format) alongside human-readable text, boosting accessibilit

What is the purpose of the <progress> element?What is the purpose of the <progress> element?Mar 21, 2025 pm 12:34 PM

The article discusses the HTML <progress> element, its purpose, styling, and differences from the <meter> element. The main focus is on using <progress> for task completion and <meter> for stati

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 Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool