如何让DaisyUI抽屉挤压页面内容而非作为覆盖层(SvelteKit)
问题描述
在SvelteKit应用中使用DaisyUI制作抽屉菜单时,默认抽屉会以覆盖层形式滑到页面上方,现在需要实现抽屉打开时挤压页面内容向右移动的效果。
当前使用的+layout.svelte代码如下:
<div class="drawer"> <input id="sidebar" type="checkbox" class="drawer-toggle" /> <div class="drawer-content flex flex-col"> <div class="navbar bg-base-100"> <div class="flex-none"> <label for="sidebar" aria-label="open sidebar" class="btn btn-square btn-ghost"> <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" class="inline-block w-5 h-5 stroke-current"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h16"></path></svg> </label> </div> <div class="flex-1"> <a class="btn btn-ghost text-xl">AUXCUBE</a> </div> </div> <slot /> </div> <div class="drawer-side"> <label for="sidebar" aria-label="close sidebar" class="drawer-overlay"></label> <!-- The Menu List --> <ul class="menu min-h-full bg-base-200 w-56 rounded-r-lg"> <li><a>Individual Item</a></li> <li> <details open> <summary>Parent</summary> <ul> <li><a>Child 1</a></li> <li><a>Child 2</a></li> </ul> </details> </li> <li><a>Individual Item</a></li> </ul> </div> </div>
当前默认效果:抽屉以覆盖层形式显示在页面内容上方。
解决方案
要实现抽屉挤压内容的效果,只需对代码做两处关键修改:
添加
drawer-push类启用挤压模式
给最外层的drawer容器添加drawer-push类,DaisyUI的该类会将抽屉纳入文档流,打开时抽屉会占据页面空间,从而挤压内容向右移动。移除
drawer-overlay元素
挤压模式下不需要覆盖层,点击页面内容区域即可通过原生checkbox的关联逻辑关闭抽屉。
修改后的完整代码如下:
<div class="drawer drawer-push"> <input id="sidebar" type="checkbox" class="drawer-toggle" /> <div class="drawer-content flex flex-col"> <div class="navbar bg-base-100"> <div class="flex-none"> <label for="sidebar" aria-label="open sidebar" class="btn btn-square btn-ghost"> <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" class="inline-block w-5 h-5 stroke-current"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h16"></path></svg> </label> </div> <div class="flex-1"> <a class="btn btn-ghost text-xl">AUXCUBE</a> </div> </div> <slot /> </div> <div class="drawer-side"> <!-- 移除了drawer-overlay元素 --> <ul class="menu min-h-full bg-base-200 w-56 rounded-r-lg"> <li><a>Individual Item</a></li> <li> <details open> <summary>Parent</summary> <ul> <li><a>Child 1</a></li> <li><a>Child 2</a></li> </ul> </details> </li> <li><a>Individual Item</a></li> </ul> </div> </div>
补充说明
drawer-push是DaisyUI内置的抽屉模式类,专门用于实现挤压内容的效果,无需额外编写自定义CSS。- 如果需要保留点击空白区域关闭抽屉的功能,可以不删除
drawer-overlay,但需要给它添加bg-transparent类,避免遮挡内容交互:<label for="sidebar" aria-label="close sidebar" class="drawer-overlay bg-transparent"></label>
内容的提问来源于stack exchange,提问作者Sadeem Sajid
相关产品推荐
相关产品推荐

