简体   繁体   中英

How to animate one element on top of another element in Angular 2?

In Angular 2, how do I animate one element so that it's size and position will match that of another target element? The target element's size and position is not fixed, but can vary at runtime. Attached is a complete example using jQuery. As a bonus, I'm wondering if the animation can be done without using an ElementRef ?

Codepen

See the Pen Animate element on top of another by Matthew Banz ( @battmanz ) on CodePen .

HTML

 <section> <button id="animateBlue">Animate Blue</button> <button id="randomizeOrange">Randomize Orange</button> </section> <section> <div class="ball" id="ball1"></div> <div class="ball" id="ball2"></div> </section> 

CSS

 body { margin: 0; padding: 0; } section:first-of-type { padding: 10px; text-align: center; background-color: #ccc; } .ball { border-radius: 50%; position: absolute; } #ball1 { background-color: blue; z-index: 5; } #ball2 { background-color: orange; } 

JS

 const ball1 = $('#ball1'); const ball2 = $('#ball2'); function getRandomIntInclusive(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } function randomlyAssignOrangePositionSize() { const radius = getRandomIntInclusive(10, 200); const top = getRandomIntInclusive(50, 300); const left = getRandomIntInclusive(10, 900); ball2.css({ width: radius, height: radius, top: top, left: left }); } ball1.css({ width: 50, height: 50, top: 100, left: 50 }); randomlyAssignOrangePositionSize(); $('#randomizeOrange').click(randomlyAssignOrangePositionSize); $('#animateBlue').click(function() { ball1.animate({ width: ball2.css('width'), height: ball2.css('height'), top: ball2.css('top'), left: ball2.css('left') }); }); 

I'll go ahead and answer my own question. It turns out that this is currently not possible in Angular 2 as of RC5. In order to perform the animation, I would need to compute the styles at runtime. This is currently an open feature request on Github:

Feature Request: Allow binding expression in style(), keyframes() etc...

In particular, checkout the comment by @dpix and the answer by @matsko.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM