Angular侧边栏切换显示/隐藏时页面自动滚动问题求助
Angular侧边栏切换时页面自动滚动问题
问题描述
使用Angular开发Web应用,侧边导航栏点击可跳转至页面对应章节,但切换侧边栏显示/隐藏状态时,页面会自动滚动。推测是侧边栏开关时内容宽度变化导致的异常效果。
相关代码
document-viewer.component.html
<mat-toolbar color="primary"> <button mat-icon-button (click)="sidenav.toggle()"> <mat-icon>menu</mat-icon> </button> </mat-toolbar> <mat-sidenav-container> <mat-sidenav #sidenav mode="side" [opened]="isLargeScreen"> <mat-nav-list> <a mat-list-item href="#valid-medical-prescription">Valid Medical Prescription</a> <a mat-list-item href="#presentation-original-prescription">Presentation of Original Prescription</a> <a mat-list-item href="#doctors-certificate">Doctor's Certificate</a> <a mat-list-item href="#health-certificate">Foreign Destination Certificate</a> </mat-nav-list> </mat-sidenav> <mat-sidenav-content #contentContainer> <div class="content"> <div id="valid-medical-prescription"> <h1>Valid Medical Prescription</h1> <h2>What is a valid medical prescription?</h2> <p> A valid medical prescription is a written order issued by a licensed medical professional (such as a doctor) to a pharmacist or pharmacy, allowing them to dispense a specific medication to the patient. It includes the patient's name, the medication name, dosage, frequency, and duration of treatment. </p> <h2>How to obtain a valid medical prescription?</h2> <p> To obtain a valid medical prescription, consult with a licensed medical professional in your country of residence. Explain your medical condition and the reason for your travel. The doctor will assess your needs and provide you with a prescription if deemed necessary. </p> <h2>What to expect at the foreign airport?</h2> <p> When you arrive at the foreign airport, have your valid medical prescription ready for inspection by customs officials. Make sure the prescription is clear and legible, and carry it in your carry-on luggage for easy access. Customs officers may ask you questions about your medication and verify the prescription's authenticity before allowing you to proceed. </p> </div> <div id="presentation-original-prescription"> <h1>Presentation of the original prescription at the Customs of the country of destination</h1> <h2>What is an original prescription?</h2> <p> To obtain an original prescription, you will need to make an appointment with a licensed healthcare provider and provide them with information about your medical history and any current medications you are taking. After a thorough evaluation, the healthcare provider may write a prescription for the medication you need. </p> <h2>How to obtain a certificate from health authorities?</h2> <p> To obtain a certificate from health authorities, contact the health department or ministry of the country you plan to visit. Provide them with details about your medication, valid medical prescription, and doctor's certificate. They may ask for additional information or documentation, such as proof of your medical condition or a letter from your treating physician. Once they have reviewed and approved your documents, they will issue the certificate. </p> <h2>What to expect at the foreign airport?</h2> <p> When traveling internationally with prescription medication, it is important to have an original prescription with you, as some countries may require it as proof that the medication is legally prescribed. It is recommended to carry the prescription in your carry-on luggage and not in your checked luggage. At a foreign airport, you may be asked to present your original prescription and/or declare any medication you are carrying with you. It is important to research the medication and the country's regulations beforehand to avoid any issues or delays. </p> </div> <div id="doctors-certificate"> <h1>Doctor’s Certificate endorsed by the health authorities of the country of residence</h1> <h2>What is a doctor's certificate?</h2> <p> A doctor's certificate, also known as a medical certificate or fit-to-fly certificate, is a document issued by a licensed medical professional confirming the patient's health condition and fitness for travel. It typically includes the patient's name, a brief description of their health condition, and the doctor's assessment of the patient's ability to travel safely. </p> <h2>How to obtain a doctor's certificate?</h2> <p> To obtain a doctor's certificate, schedule an appointment with a licensed medical professional in your country of residence. Inform them about your travel plans and any existing medical conditions. The doctor will perform a medical examination and issue a certificate if they determine that you are fit to travel. </p> <h2>What to expect at the foreign airport?</h2> <p> Upon arrival at the foreign airport, have your doctor's certificate ready for inspection by customs or health officials. They may ask you questions about your health condition and travel plans. The certificate should be endorsed by the health authorities of your country of residence to ensure smooth processing. </p> </div> <div id="health-certificate"> <h1>Certificate issued by the health authorities of the country of destination</h1> <h2>What is a certificate from health authorities?</h2> <p> A certificate from health authorities is a document issued by the health department or ministry of the destination country. It verifies that the traveler's medication is allowed in the country and may include information about any restrictions or requirements related to the medication. </p> <h2>How to obtain a certificate from health authorities?</h2> <p> To obtain a certificate from health authorities, contact the health department or ministry of the country you plan to visit. Provide them with details about your medication, valid medical prescription, and doctor's certificate. They may ask for additional information or documentation, such as proof of your medical condition or a letter from your treating physician. Once they have reviewed and approved your documents, they will issue the certificate. </p> <h2>What to expect at the foreign airport?</h2> <p> When you arrive at the foreign airport, present your certificate from health authorities to the customs officials. They may verify the document's authenticity and ask you questions about your medication or medical condition. Ensure that you have all the necessary paperwork and be prepared to answer any questions. Once your documents are verified, you should be allowed to proceed with your medication. </p> </div> </div> </mat-sidenav-content> </mat-sidenav-container>
document-viewer.component.scss
mat-toolbar { box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); } mat-sidenav-container { height: 100%; position:fixed; } mat-sidenav { padding-top: 85px; width: 350px; background-color: #ffffff; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); } mat-sidenav-content { padding: 1rem; } mat-nav-list a{ font-size: 30px; margin-bottom: 50px; } .content{ margin: 0 200px; padding-bottom: 100px; }
document-viewer.component.ts
import { Component, OnInit, ViewChild } from '@angular/core'; import { MatSidenav } from '@angular/material/sidenav'; import { BreakpointObserver, Breakpoints } from '@angular/cdk/layout'; @Component({ selector: 'app-document-viewer', templateUrl: './document-viewer.component.html', styleUrls: ['./document-viewer.component.scss'] }) export class DocumentViewerComponent implements OnInit { @ViewChild('sidenav') sidenav!: MatSidenav; isLargeScreen!: boolean; constructor(private breakpointObserver: BreakpointObserver) {} ngOnInit() { this.breakpointObserver .observe([Breakpoints.Handset, Breakpoints.Tablet]) .subscribe(result => { this.isLargeScreen = !result.matches; if (!this.isLargeScreen) { this.sidenav.close(); } }); } }
解决方案
1. 禁用MatSidenavContainer的自动滚动
Angular Material的mat-sidenav-container在侧边栏切换时会默认调整滚动位置,通过CSS禁用该行为:
修改document-viewer.component.scss中的mat-sidenav-container样式:
mat-sidenav-container { height: 100%; position: fixed; overflow: auto; /* 添加此属性 */ }
2. 手动控制滚动位置(备选方案)
如果上述方法无效,可在切换侧边栏前后手动保存并恢复滚动位置:
- 修改TS文件,添加滚动位置保存/恢复逻辑:
import { Component, OnInit, ViewChild } from '@angular/core'; import { MatSidenav } from '@angular/material/sidenav'; import { BreakpointObserver, Breakpoints } from '@angular/cdk/layout'; @Component({ selector: 'app-document-viewer', templateUrl: './document-viewer.component.html', styleUrls: ['./document-viewer.component.scss'] }) export class DocumentViewerComponent implements OnInit { @ViewChild('sidenav') sidenav!: MatSidenav; isLargeScreen!: boolean; private scrollPosition = 0; constructor(private breakpointObserver: BreakpointObserver) {} ngOnInit() { this.breakpointObserver .observe([Breakpoints.Handset, Breakpoints.Tablet]) .subscribe(result => { this.isLargeScreen = !result.matches; this.saveScrollPosition(); if (!this.isLargeScreen) { this.sidenav.close().then(() => this.restoreScrollPosition()); } else { this.sidenav.open().then(() => this.restoreScrollPosition()); } }); } toggleSidenav() { this.saveScrollPosition(); this.sidenav.toggle().then(() => this.restoreScrollPosition()); } private saveScrollPosition() { this.scrollPosition = window.scrollY || document.documentElement.scrollTop; } private restoreScrollPosition() { window.scrollTo(0, this.scrollPosition); } }
- 更新HTML中的按钮点击事件:
<button mat-icon-button (click)="toggleSidenav()"> <mat-icon>menu</mat-icon> </button>
3. 优化内容容器的宽度适配
当前.content的固定左右margin会导致侧边栏切换时内容宽度突变,触发浏览器自动滚动。修改为自适应宽度:
.content{ max-width: 1200px; /* 固定最大宽度,避免过宽 */ margin: 0 auto; /* 水平居中 */ padding-bottom: 100px; }
内容的提问来源于stack exchange,提问作者Dan1341_az
相关产品推荐
相关产品推荐

