问题描述: 在Angular 7应用程序中,普通锚链接(#)无法起作用。当点击锚链接时,页面不会滚动到相应的位置。
解决方法: 要使普通锚链接在Angular应用程序中起作用,需要进行以下步骤。
确保你的锚链接的href属性值与目标元素的id属性值相匹配。例如,如果目标元素的id为"section1",则锚链接的href应为"#section1"。
在组件的构造函数中注入Angular的Router模块,并使用其方法来处理锚链接的点击事件。
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
@Component({
selector: 'app-your-component',
templateUrl: './your-component.component.html',
styleUrls: ['./your-component.component.css']
})
export class YourComponent implements OnInit {
constructor(private router: Router) { }
ngOnInit() {
}
scrollToElement(elementId: string): void {
const element = document.getElementById(elementId);
if (element) {
element.scrollIntoView({ behavior: 'smooth', block: 'start', inline: 'nearest' });
}
}
}
Go to Section 1
这样,当点击锚链接时,会调用scrollToElement方法,并将相应的目标元素的id传递给它。然后,使用scrollIntoView方法将页面滚动到目标元素所在的位置。
请确保在使用scrollIntoView方法之前,目标元素已经加载,否则将无法正常工作。
希望以上解决方法能帮助到你解决问题。