import { Component, OnInit, Input, ElementRef, Output, EventEmitter } from '@angular/core' @Component({ selector: 'farris-doc-anchor', templateUrl: './anchor.component.html', styleUrls: ['./anchor.component.scss'] }) export class AnchorComponent implements OnInit { @Input() anchorBallTop: number @Input() elRef: any @Output() scrollTo = new EventEmitter() anchorDom: any anchor_ink_ball: any isShowAnchorInkall: boolean anchorsList = [] constructor(private el: ElementRef) {} ngOnInit() { const titleDomArr = this.elRef.querySelectorAll('.markdown-title') titleDomArr.forEach(element => { setTimeout(() => { this.anchorsList.push({ name: element.innerText, offsetTop: element.offsetTop }) }, 0) }) } ngAfterViewInit(): void { this.anchor_ink_ball = this.el.nativeElement.querySelector( '.anchor-ink-ball' ) setTimeout(() => { this.anchorDom = this.el.nativeElement.querySelectorAll( '.anchor-link' ) if ( this.anchorsList.length > 0 && this.anchorsList[0].offsetTop < 100 ) { this.anchor_ink_ball.style.top = this.anchorDom[0].offsetTop + 10 + 'px' this.isShowAnchorInkall = true } }, 0) } ngOnChanges() { if (this.anchorBallTop !== undefined && this.anchorsList.length > 0) { // if (this.anchorsList[0].offsetTop < 100) { // console.log(this.anchorDom) // this.anchor_ink_ball.style.top = // this.anchorDom[0].offsetTop + 10 + 'px' // this.isShowAnchorInkall = true // } let _top this.anchorsList.forEach((item, index) => { if (item.offsetTop < this.anchorBallTop + 100) { _top = index } }) this.anchor_ink_ball.style.top = this.anchorDom[_top].offsetTop + 10 + 'px' this.isShowAnchorInkall = true } } goto(offset) { this.scrollTo.emit(offset) } }