Vue 让元素抖动/摆动起来的实现代码

2020-06-14 06:03:31易采站长站整理

修改元素位置:


/**
* 修改元素位置
* @param x
* @param y
* @param z
*/
jitterView({ x = 0, y = 0, z = 0 }) {
this.$el.style.transform = `translate3d(${x}px, ${y}px, ${z}px)`;
},

这里需要判断需要 Z 轴摆动吗? 当需要时,必须给当前元素的父级添加 perspective, 从而修改子级透视效果


mounted() {
// 如果要执行 z 轴动画需要设置父级,从而修改子级透视效果,否则 Z 轴没有效果
if (this.range.z > 0) {
const parentEl = this.$el.parentNode;
Object.keys(this.perspectiveStyle).forEach((key) => {
parentEl.style[key] = this.perspectiveStyle[key];
});
}
},

最后看看可以传的属性:


props: {
// 抖动范围,单位是px, 例如:{x: 4, y: 2, z: 10}
range: {
type: Object,
default: () => { return { z: 8 }; },
},
start: {
type: Boolean,
required: true,
},
shiftPercent: {
type: Number,
default: 0.1, // 移动range中初始值的百分比
},
perspectiveStyle: {
type: Object,
default: () => {
return {
perspective: '300px',
perspectiveOrigin: 'center center'
};
}
}
},

上面是可以传的属性,大家可以按照情况修改

最后:

这里我只写了简单的动画,也可以根据不同情况进行修改,从而达到想要的效果。这里已经满足输入框错误抖动的效果了。