css - Angular - 侧边栏导航
问题描述
我试图从左侧导航中创建一个幻灯片,而不是传统的引导程序在折叠时向下滑动导航。
切换按钮的 HTML
<button id="collapseBtn" class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation" (click)="toggleSideBar()" >
Toggle</button>
侧边栏的 HTML
<div class="sidebar">
<ul>
<li>S-Dashboard</li>
<li>S-Voucher</li>
</ul>
</div>
侧边栏的 CSS
.sidebar {
background: #1a2580;
color: white;
height: 100%;
width: 0;
position: fixed;
z-index: 1;
top: 0;
left: 0;
overflow-x: hidden;
padding-top: 60px;
transition: 0.5s;
}
.showsidebar {
width: 250px;
}
.hidesidebar {
width: 0px;
}
组件文件中的 ToggleSideBar 函数
toggleSideBar() {
document.getElementsByClassName('sidebar')[0].classList.add('showsidebar');
this.sideBarOpen = true;
}
单击切换按钮会根据需要滑出导航,但不会将内容推到右侧。结果,内容隐藏在侧边栏下方。
如何将内容向右推送?
其次,我尝试在单击页面上的任何位置时使用 HostListener 关闭侧边栏,但这似乎不起作用。
解决方案
body
当您切换侧边菜单时,您可以切换应该负责移动(推送)整个页面内容的元素上的类。
样式.css
body {
position: relative;
overflow: hidden;
transition: left 0.5s ease; /* Animation styles are just for demo */
left:0;
}
body.push {
left:250px;
}
并在您的组件中:
import { Component, OnInit, HostListener, ElementRef } from '@angular/core';
@Component({
selector: 'app-topnav',
templateUrl: './topnav.component.html',
styleUrls: ['./topnav.component.css']
})
export class TopnavComponent implements OnInit {
isMenuSmall:boolean = true;
sideBarOpen: boolean = false;
constructor(private el:ElementRef) { }
// Your initial click listener on the host element
@HostListener('click', ['$event'])onClick(event) {
event.stopPropagation();
if (event.target.id == "collapseBtn") {
document.getElementsByClassName('sidebar')[0].classList.add('showsidebar');
document.body.classList.add('push');
this.sideBarOpen = true;
} else {
if (this.sideBarOpen) {
document.getElementsByClassName('sidebar')[0].classList.remove('showsidebar');
document.body.classList.remove('push');
this.sideBarOpen = false;
}
}
}
// Click listener on the window object to handle clicks anywhere on
// the screen.
@HostListener('window:click', ['$event']) onOutsideClick(event){
if(this.sideBarOpen && !this.el.nativeElement.contains(event.target)){
this.sideBarOpen=false;
document.getElementsByClassName('sidebar')[0].classList.remove('showsidebar');
document.body.classList.remove('push');
}
}
ngOnInit() {
}
toggleSideBar() {
}
}
当然,上面的代码可以额外增强,但我希望它向您展示了您想要实现的目标的方法。
推荐阅读
- c# - C# 使用参数触发 Jenkins 作业
- excel - 创建 VBA If Then 循环遍历单元格范围
- node.js - 重定向到最后一页用户在登录 node.js 和 express 后打开(没有护照)
- angular - 如何逐行显示div - 模板Angular
- java - 如何在 Handlebars.java 中指定选项参数?
- python - 我想提取列表中的元素以在 HTML 上显示
- python - 尝试比较 IP 地址但不熟悉返回类型
- ios - Firebase 性能 | 控制台中不显示任何数据
- c# - 带有 Asp.Net Core 2.1 的 Serilog 不从 appsettings.json 写入
- c# - 为较新的 Windows.Web.Http.HttpClient 处理 IHttpFilter 实现中的 4XX 错误