首先展示一下效果,狠狠點擊 https://zhangkunusergit.github.io/vue-component/dist/jitter.html
代碼github : https://github.com/zhangKunUserGit/vue-component
轉載請標注: https://www.cnblogs.com/zhangkunweb/p/vue_jitter.html
先說一下用法:
<jitter :start.sync="抖動控制器" :range="{ 包含x,y, z }" :shift-percent="0.1"> 這里是你要抖動的元素 </jitter>
思路:
1.抖動就是擺動,現實中的鍾擺可以很形象。
2.當擺動到臨界點后,就會向相反的方向擺動。
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); },
這里准備動畫開始前的工作。
執行動畫:
// 持續抖動 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); },
執行動畫,當判斷已經無力擺動后,讓元素回歸到原來的位置,並清除動畫。
修改元素位置:
/** * 修改元素位置 * @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' }; } } },
上面是可以傳的屬性,大家可以按照情況修改
最后:
這里我只寫了簡單的動畫,也可以根據不同情況進行修改,從而達到想要的效果。這里已經滿足輸入框錯誤抖動的效果了。