Vue菜单项点击添加蓝色边框和背景色
<h2>Vue.js实现菜单项点击蓝色边框和背景色变化</h2>
<p>本文介绍如何使用Vue.js在点击菜单项时,为其添加蓝色边框并更改背景色,以增强用户交互体验。</p>
<h3>代码示例html<template> <view> <view class='af-head'> <span class='af-head-msg' style='font-size: 60rpx;'><</span> <span class='af-head-msg af-head-fuc'>全部功能</span> </view></h3>
<pre><code><view class='sidebar'> <ul> <li @click='selectMenuItem(1)' :class='{ active: activeMenuItem === 1 }'>菜单项1</li> <li @click='selectMenuItem(2)' :class='{ active: activeMenuItem === 2 }'>菜单项2</li> <li @click='selectMenuItem(3)' :class='{ active: activeMenuItem === 3 }'>菜单项3</li> </ul> </view> </view></template>
</code></pre>
<script>export default { data() { return { activeMenuItem: null // 当前选中的菜单项 }; }, methods: { selectMenuItem(item) { this.activeMenuItem = item; } }};</script>
<style>.af-head { position: relative; background-color: #629ffc; height: 100rpx; display: flex; justify-content: center; font-size: 44rpx; font-weight: 500; font-family: sans-serif;}
.af-head-msg { position: absolute; bottom: 16rpx; color: white; left: 38rpx;}
.af-head-fuc { text-align: center; left: 300rpx;}
.sidebar { width: 100px; background-color: white; height: 100vh; padding-top: 20rpx;}
.sidebar ul { list-style: none; padding: 0; margin: 0;}
.sidebar li { padding: 10rpx; color: black; list-style-type: none; display: block; margin-top: 10px; cursor: pointer; transition: background-color 0.3s; /* 添加过渡效果 */}
.sidebar li.active { border-left: 4px solid #629ffc; /* 添加左边框样式 */ background-color: #f0f0f0; /* 更改背景色 */}</style>
<h3>代码解析</h3>
<ol>
<li><strong>数据绑定:</strong> 使用 <code>:class='{ active: activeMenuItem === 1 }'</code> 动态绑定 <code>active</code> 类名,根据 <code>activeMenuItem</code> 的值决定是否应用该样式。2. <strong>事件处理:</strong> 通过 <code>@click='selectMenuItem(1)'</code> 绑定点击事件,更新 <code>activeMenuItem</code> 的值。3. <strong>样式定义:</strong> - <code>.sidebar li.active</code> 定义选中状态下的样式,包括蓝色左边框和背景色。 - <code>.sidebar li</code> 添加 <code>transition</code> 属性,实现平滑的过渡效果。</li>
</ol>
<p>通过上述代码,您可以轻松实现点击菜单项时添加蓝色边框和更改背景色的效果,提升用户体验。</p>
原文地址: https://www.cveoy.top/t/topic/RT0 著作权归作者所有。请勿转载和采集!