【概要】
クリックするとお化けの画像が現れ、マウスカーソルの移動に合わせてお化けの画像も移動するボタンを作りました。
【動作結果】
【コード】
上記リンク先と同じコード
App.vue
<template>
<div v-show="visible" class="ghost" :style="updatePosition">
<!-- お化けの画像は下記リンク先のSVGコードをそのままコピーしたもの
https://fontawesome.com/icons/ghost?f=classic&s=solid -->
<svg xmlns="http://www.w3.org/2000/svg" height="1em" viewBox="0 0 384 512">
<!--! Font Awesome Free 6.4.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license (Commercial License) Copyright 2023 Fonticons, Inc. -->
<path
d="M40.1 467.1l-11.2 9c-3.2 2.5-7.1 3.9-11.1 3.9C8 480 0 472 0 462.2V192C0 86 86 0 192 0S384 86 384 192V462.2c0 9.8-8 17.8-17.8 17.8c-4 0-7.9-1.4-11.1-3.9l-11.2-9c-13.4-10.7-32.8-9-44.1 3.9L269.3 506c-3.3 3.8-8.2 6-13.3 6s-9.9-2.2-13.3-6l-26.6-30.5c-12.7-14.6-35.4-14.6-48.2 0L141.3 506c-3.3 3.8-8.2 6-13.3 6s-9.9-2.2-13.3-6L84.2 471c-11.3-12.9-30.7-14.6-44.1-3.9zM160 192a32 32 0 1 0 -64 0 32 32 0 1 0 64 0zm96 32a32 32 0 1 0 0-64 32 32 0 1 0 0 64z"
/>
</svg>
</div>
<button @click="visible = !visible">押しちゃダメ!</button>
</template>
<script setup lang="ts">
import { onMounted, onUnmounted, ref, computed } from 'vue'
const visible = ref(false)
const left = ref(0)
const top = ref(0)
// マウス移動のイベントからマウスの位置を取得
const update = (e) => {
left.value = e.pageX
top.value = e.pageY
}
// 取得したマウスの位置をCSS用に書き換える
const updatePosition = computed(() => {
return {
left: left.value + 'px',
top: top.value + 'px',
}
})
onMounted(() => window.addEventListener('mousemove', update))
onUnmounted(() => window.removeEventListener('mousemove', update))
</script>
<style scoped>
/* お化け画像がいい感じの位置に配置され動くようにrelative指定
widthとheightはボタン押下時のdiv要素表示タイミングで、ボタンの位置がずれないようにするため
*/
.ghost {
position: relative;
width: 0px;
height: 0px;
}
</style>