考虑以下代码:
<div class="red-square"
*ngIf="someCondition"
[@showHideAnimation]
></div>
有没有办法让上述 div 以随机动画消失?
随机动画,例如,将对象旋转任意 Angular ,例如 30 到 150 度之间。
最佳答案
我有一个想法,但它本身并不是随机的。。
给定你的动画
animations: [
trigger('animationName', [
state('void', style({
// hidden case
})),
state('*', style({
// visible case
})),
transition(':enter', animate('TIME [DELAY] EASING')),
transition(':leave', animate('TIME [DELAY] EASING'))
])
]
你可以做的是像这样创建一个全局函数
function randomizeAnimation(propertiesNumber: number, state: number) {
let properties = ['borderBottom', 'opacity', 'All of the properties you want to animate here'];
let randomIndex = () => Math.random() * properties.length;
let style = {};
for (let i = 0; i < propertiesNumber; i++) {
let index = randomIndex();
let voidValue = '0';
let showValue = '*';
// Why it's not "randomized" : you need to make custom rules here. Example : colors
if (properties[index].toLowerCase().includes('color')) {
let RdmOct = () => Math.random() * 256;
let generateRandomColor = () => `rgb(${RdmOct()}, ${RdmOct()}, ${RdmOct()})`;
voidValue = generateRandomColor();
showValue = generateRandomColor();
}
style[properties[index]] = state ? voidValue : showValue;
}
return style;
}
此函数的作用是需要多个属性来设置动画,以及一个动画状态( bool 值或 0/1)。然后它在其数组中选择随机属性,使其成为“随机”。如果属性有特殊的用例,例如颜色(通配符“*”不起作用),那么您必须处理它。创建随机样式后,它会将其返回以在动画函数中使用。它不像 Math.random() 那样“随机”,但它可以做到这一点!
在您的组件中,您现在可以在动画中调用此函数:
animations: [
trigger('animationName', [
state('void', style(randomizeAnimation(1, 0))),
state('void', style(randomizeAnimation(1, 1))),
transition(':enter', animate('275ms ease-out')),
transition(':leave', animate('275ms ease-in'))
])
]
我不确定它是否有效,但我想这已经足够满足您的需求了!
编辑您甚至可以通过在动画中设置间隔来更进一步,每分钟左右更改动画。但如果这个方法根本不起作用……我就不会浪费更多的时间来写这个了啊哈哈
关于javascript - Angular 中的随机动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47203608/