【发布时间】:2016-08-24 05:17:34
【问题描述】:
在 Angular 2 中,如何为一个元素设置动画,使其大小和位置与另一个目标元素匹配?目标元素的大小和位置不是固定的,但可以在运行时变化。附件是一个使用 jQuery 的完整示例。作为奖励,我想知道是否可以在不使用 ElementRef 的情况下完成动画?
Codepen
请参阅CodePen 上 Matthew Banz (@battmanz) 的 Pen Animate element on top of another。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')
});
});
【问题讨论】:
标签: javascript angular angular2-animation