如何将Svelte侧边栏当前激活元素背景设为透明以透出主内容背景
实现思路
将原有「给激活菜单项叠加白色背景」的逻辑反转,改为给侧边栏整体背景挖掉和激活项形状完全匹配的透明区域,即可实现背景图透出的效果,同时保留侧边栏右侧的圆角缺口样式。
代码修改步骤
1. 脚本部分新增激活项位置计算
在<script>中添加激活项偏移量的动态计算逻辑,用于CSS变量传值:
// 原有代码保留,新增以下内容 let activeEl: HTMLElement | null; $: { // 匹配激活的菜单项 const matchedItem = sidebarItems.find(item => window.location.pathname === item.path); if (matchedItem && activeEl) { // 动态获取激活项的顶部偏移量,适配非固定高度的场景 const activeTop = `${activeEl.offsetTop}px`; sidebar.style.setProperty('--active-top', activeTop); } else { // 无激活项时移除挖空样式 sidebar.style.removeProperty('--active-top'); } }
然后给遍历生成的<a>标签绑定bind:this:
{#each sidebarItems as item} <a class="sidebar-item" class:active={window.location.pathname == item.path} href={item.path} bind:this={window.location.pathname == item.path ? activeEl : null} > <!-- 内部原有代码保留 --> </a> {/each}
2. CSS部分修改
调整侧边栏基础样式,新增mask挖空逻辑:
.sidebar { padding: 0; color: var(--forecolor); background-color: var(--background-color); margin: 0; width: 5rem; height: 100vh; position: fixed; z-index: 100; display: flex; flex-direction: column; transition: 0.2s ease; /* 新增挖空相关配置 */ --mask-radius: 30px; -webkit-mask-composite: xor; mask-composite: exclude; } /* 存在激活项时应用挖空mask */ .sidebar[style*="--active-top"] { -webkit-mask-image: linear-gradient(#000 0 0), radial-gradient(circle at top right, transparent var(--mask-radius), #000 var(--mask-radius)), radial-gradient(circle at bottom right, transparent var(--mask-radius), #000 var(--mask-radius)); -webkit-mask-size: 100% 100%, 100% calc(var(--mask-radius) * 2), 100% calc(var(--mask-radius) * 2); -webkit-mask-position: 0 0, 0 calc(var(--active-top) - var(--mask-radius)), 0 calc(var(--active-top) + 5rem - var(--mask-radius)); -webkit-mask-repeat: no-repeat; mask-image: linear-gradient(#000 0 0), radial-gradient(circle at top right, transparent var(--mask-radius), #000 var(--mask-radius)), radial-gradient(circle at bottom right, transparent var(--mask-radius), #000 var(--mask-radius)); mask-size: 100% 100%, 100% calc(var(--mask-radius) * 2), 100% calc(var(--mask-radius) * 2); mask-position: 0 0, 0 calc(var(--active-top) - var(--mask-radius)), 0 calc(var(--active-top) + 5rem - var(--mask-radius)); mask-repeat: no-repeat; }
修改激活项样式,删除原有伪元素逻辑:
.sidebar-item.active { margin-left: 0.2rem; /* 去掉原有白色背景,文字颜色可根据背景图对比度调整,可加text-shadow保证可读性 */ color: #fff; text-shadow: 0 0 2px rgba(0,0,0,0.8); /* 删除原有::before、::after伪元素的全部代码 */ }
注意事项
- 如果需要适配登出按钮的激活状态,给登出按钮的容器也加上
bind:this判断即可。 - 若菜单项高度不是固定5rem,将mask位置计算里的
5rem替换为动态获取的激活项高度即可。 - mask属性兼容Chrome 76+、Firefox 105+、Safari 15.4+,覆盖绝大多数主流设备。
内容的提问来源于stack exchange,提问作者DeltaRays
相关产品推荐
相关产品推荐

