fontawesomeでiタグをクリックした時にテキストがアニメーションするやつの実装
今回はvue.jsで実装する。
x方向y方向に拡大縮小するrubberbandというアニメーションらしい。
テンプレートとスクリプト
<template>
<p v-bind:class="{ bounce: bounceAnimation }" @click="copyText">
{{text}}
</p>
<input type="hidden" id="text" :value="text">
</template>
<script>
export default {
data: () => ({
text: 'コピー対象テキスト',
bounceAnimation: false,
}),
methods: {
bounceAnimationInactive() {
this.bounceAnimation = false
},
copyText() {
let testingCodeToCopy = document.querySelector('#text')
testingCodeToCopy.setAttribute('type', 'text')
testingCodeToCopy.select()
try {
var successful = document.execCommand('copy');
if (successful) {
// コピー成功
this.bounceAnimation = true
} else {
// コピー失敗メッセージ
}
} catch (err) {
// エラーメッセージ
}
/* unselect the range */
testingCodeToCopy.setAttribute('type', 'hidden')
window.getSelection().removeAllRanges()
// アニメーションが終わるまで待つ
setTimeout(this.bounceAnimationInactive, 3000);
},
}
}
</script>
クリックしたらcopyTextが発火してテキストコピー処理を行い、bounceAnimationをtrueにしpタグのclassにバインドしてあるbounceをactiveにする。そして、setTimeoutでアニメーションの終了を待つというかんじ。
css
.bounce {
animation-duration: 1s;
animation-fill-mode: both;
animation-iteration-count: 1;
animation-name: rubberBand;
}
.rubberBand {
-webkit-animation-name: rubberBand;
animation-name: rubberBand;
}
@keyframes rubberBand {
from {
transform: scale3d(1, 1, 1);
}
10% {
transform: scale3d(1.05, 0.75, 1);
}
20% {
transform: scale3d(0.85, 1.15, 1);
}
30% {
transform: scale3d(1.02, 0.85, 1);
}
45% {
transform: scale3d(.95, 1.05, 1);
}
75% {
transform: scale3d(1.02, .95, 1);
}
to {
transform: scale3d(1, 1, 1);
}
}
cssは簡単でx方向y方向に拡大縮小しているだけ
まとめ
「css テキスト クリック アニメーション」で検索してもなかなか出てこなかった。
animate.cssを導入するほどでもなかったのでスクラッチで書いた。