在 Vue 3 中实现卡片悬浮发光效果,可以利用现代 CSS 和 Vue 组件特性来完成。以下是一个详细的实现步骤和代码示例。
实现步骤
- 设置 Vue 3 项目
- 创建卡片组件
- 添加悬浮发光效果的 CSS
- 使用组件
1. 设置 Vue 3 项目
确保你已经创建了一个 Vue 3 项目。如果还没有创建,可以使用 Vue CLI 来创建:
npm install -g @vue/cli
vue create my-vue-project
cd my-vue-project
npm run serve
2. 创建卡片组件
在 src/components
目录下创建一个名为 GlowingCard.vue
的文件。
GlowingCard.vue
<template>
<div class="card">
<div class="card-content">
<h2>酷炫卡片</h2>
<p>这是一个带有悬浮发光效果的卡片。</p>
</div>
</div>
</template>
<script>
export default {
name: 'GlowingCard'
}
</script>
<style scoped>
.card {
width: 300px;
height: 200px;
background: #fff;
border-radius: 10px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
transition: transform 0.3s, box-shadow 0.3s;
position: relative;
margin: 20px;
cursor: pointer;
}
.card:hover {
transform: translateY(-10px);
box-shadow: 0 12px 24px rgba(0, 0, 0, 0.2);
}
.card-content {
padding: 20px;
text-align: center;
}
.card::before {
content: '';
position: absolute;
top: 50%;
left: 50%;
width: 100%;
height: 100%;
background: radial-gradient(circle, rgba(255,255,255,0.3) 0%, rgba(255,255,255,0) 80%);
opacity: 0;
transition: opacity 0.3s;
transform: translate(-50%, -50%);
border-radius: 10px;
z-index: 0;
}
.card:hover::before {
opacity: 1;
}
</style>
3. 添加悬浮发光效果的 CSS
在 GlowingCard.vue
中,我们使用以下 CSS 技巧实现悬浮发光效果:
- 基础样式:设置卡片的宽高、背景色、边框圆角和阴影。
- 悬浮效果:使用
transform
和box-shadow
实现卡片的悬浮效果。 - 发光效果:通过
::before
伪元素创建一个渐变背景来模拟发光效果。 - 过渡效果:利用
transition
实现平滑的效果变化。
4. 使用组件
在 src/App.vue
文件中使用 GlowingCard
组件。
App.vue
<template>
<div id="app">
<h1>Vue 3 卡片悬浮发光效果</h1>
<GlowingCard />
</div>
</template>
<script>
import GlowingCard from './components/GlowingCard.vue';
export default {
name: 'App',
components: {
GlowingCard
}
}
</script>
<style>
#app {
text-align: center;
font-family: Avenir, Helvetica, Arial, sans-serif;
color: #2c3e50;
margin-top: 60px;
}
</style>
总结
以上代码展示了如何在 Vue 3 中创建一个带有悬浮发光效果的卡片。利用 CSS 的 box-shadow
、transform
和 ::before
伪元素,你可以创建现代、动态的视觉效果。这种效果不仅可以用于卡片,也可以扩展到其他 UI 组件中,提升用户体验。你可以根据需求调整样式,添加更多的内容和功能。