[英]Get id of each element when scroll to top in Angular
我想在 section 元素到達頂部時獲取它的 id。 已經用jquery做了類似的事情,但我想用 Angular 做同樣的事情。 我以類似的方式嘗試過,但沒有成功。
/*let content = document.getElementsByClassName('scrollable'); this.listener = this.renderer2.listen('window', 'scroll', (e) => { let elementPos = el.getBoundingClientRect().top + window.pageYOffset; var el = Array.prototype.forEach.call(content, (el)=>{ // console.log(el.id, el.getBoundingClientRect().bottom, parseInt(el.clientHeight)) if(el.getBoundingClientRect().bottom >= parseInt(el.clientHeight)) { console.log({el}) } }) */
section {background: #ccc; height: 100vh;}; section:nth-child(odd) {background: red}
<section class="scrollable" id="scroll1"> Scroll1 </section> <section class="scrollable" id="scroll2"> Scroll2 </section> <section class="scrollable" id="scroll3"> Scroll3 </section> <section class="scrollable" id="scroll4"> Scroll4 </section> <section class="scrollable" id="scroll5"> Scroll5 </section>
我做了這個stackblitz 。
我存儲了部分的offsetTop
並添加了一個偵聽器以在窗口上滾動並檢查它是否達到閾值。
我可以通過一點點實驗讓它自己工作。 下面的代碼可能會有所幫助。 謝謝
let content = document.getElementsByClassName('scrollable');
// let windowTop = window.scroll.offset()
this.listener = this.renderer2.listen('window', 'scroll', (e) => {
let scrollY = this.windowRef.nativeWindow.pageYOffset;
let landingPage = Array.prototype.filter.call(content, (el)=>{
// console.log(el.id, scrollY, el.getBoundingClientRect().top)
return scrollY > (el.getBoundingClientRect().top + window.pageYOffset - 80);
})
// console.log({landingPage})
console.log(landingPage.at(-1).id)
});
......編輯......
我嘗試更正@Mahdi Zarei 代碼並得到了一些結果。 stackblitz 演示
import { AfterViewInit, Component, VERSION } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent implements AfterViewInit {
constructor() {}
ngAfterViewInit() {
// @ts-ignore
const sections : any = Array.from(
document.getElementsByClassName('scrollable') as HTMLCollectionOf<HTMLElement>
).map((section) => [section.id, section.offsetTop]);
window.addEventListener('scroll', function (ev) {
let foundIndex = 0;
sections.forEach((sec, index) => {
if (document.scrollingElement.scrollTop >= sec[1]) {
foundIndex = index;
}
});
document.getElementById('el').innerText = sections[foundIndex][0];
});
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.