如果在vue中實現一個輸入框的抖動效果?


1. 先來理下思路?

1)抖動就是擺動,現實中的鍾擺可以很形象。
2)當擺動到臨界點后,就會向相反的方向擺動。
3)在沒有動力時,擺動會慢慢停止。

2.用法:


:start.sync 里面是抖動器名字(不同name), :range ={包含x,y, z}

3.初始化抖動

initJitter() {
// 把start變成false, 方便下次點擊
this.$emit('update:start', false);
// 清除上次動畫
this.clearAnimate();
// 設置currentRange, 填充this.range 中沒有的項
this.currentRange = Object.assign({}, { x: 0, y: 0, z: 0 }, this.range);
// 獲取需要操作的的項 和 每次需要擺動的量
const { position, shiftNumber } = this.getPositionAndShiftNumber();
this.position = position;
this.shiftNumber = shiftNumber;
// 初始 move 起始點是0
this.move = { x: 0, y: 0, z: 0 };
// 初始時 是順時針
this.isClockwise = true;
// 執行動畫
this.timer = window.requestAnimationFrame(this.continueJitter);
},

4.執行動畫:

// 持續抖動
continueJitter() {
this.refreshMove(this.isClockwise ? -1 : 1);
// 絕對值
const absMove = this.getAbsMove();
const currentRange = this.currentRange;
let changeDirection = false;
for (let i = 0, l = this.position.length, p; i < l; i += 1) {
p = this.position[i];
// 判斷是否到達臨界值,到達后 應該反方向執行動畫
if (currentRange[p] <= absMove[p]) {
// 等比例縮減
this.currentRange[p] -= this.shiftNumber[p];
// 判斷如果已經無力再擺動,就讓擺動停止, 只要有一個值達到了0,所有都會達到
if (this.currentRange[p] <= 0) {
// 停止在起始點上
this.jitterView({ x: 0, y: 0, z: 0 });
// 清除動畫
this.clearAnimate();
return;
}
// 更新move為臨界點
this.move[p] = this.isClockwise ? -this.currentRange[p] : this.currentRange[p];
// 改變擺動方向
changeDirection = true;
}
}
if (changeDirection) {
// 擺動方向取反
this.isClockwise = !this.isClockwise;
}
// 更新元素位置
this.jitterView(this.move);
// 繼續執行動畫
this.timer = window.requestAnimationFrame(this.continueJitter);
},

5.修改元素位置:

jitterView({ x = 0, y = 0, z = 0 }) {
this.$el.style.transform = translate3d(${x}px, ${y}px, ${z}px);
},

6.需要時,必須給當前元素的父級添加 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];
});
}
},

7.傳入的屬性

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'
};
}
}
},

參考原文:https://www.cnblogs.com/zhangkunweb/p/vue_jitter.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2026 CODEPRJ.COM