gpt4 book ai didi

html - 在 Angular 6 中使用 @ViewChild 创建粘性元素 - 无法获取元素的位置

转载 作者:太空狗 更新时间:2023-10-29 18:09:21 26 4
gpt4 key购买 nike

我正在使用 Angular 6 尝试创建一个 HTML 元素(表格标题),该元素位于页面中间,但当用户滚动到该点时将停留在页面顶部。我正在尝试使用 @ViewChild 获取该元素的位置,但无法检索它。可能缺少什么?

目前,始终应用“粘性”类,但我只想在元素的位置 <= 到 window.pageYOffset 时应用粘性类。

我正在尝试实现与 THIS 类似的效果使用 THIS教程。

我的 HTML:

<table id="tabletop" class="table" >
<thead >
<tr #stickyMenu [class.sticky] = "stickyMenu" >
<th scope="col" id="th0">Monitoring Point</th>
<th scope="col" id="th1">Network Health<br><small id="more_detail">(Click icon to see more detail)</small></th>
<th scope="col" id="th2">Active Alerts</th>
<th scope="col" id="th3">Velocity (ft/s)</th>
<th scope="col" id="th4">Water Temperature (°F)</th>
<th scope="col" id="th5">Depth Readings (m)</th>
</tr>
</thead>
</table>

CSS:

.sticky{
position: fixed;
top: 0;
/* overflow: hidden; */
z-index: 10;
background-color: #fff;
width:100%;
padding-right:20px!important;
}

我的组件:

import { Component, OnInit, ViewChild , ViewEncapsulation, HostListener, ElementRef, AfterViewInit} from '@angular/core';
import { ActivatedRoute, ParamMap, Router } from '@angular/router';
import { AuthService } from '../../services/auth.service';
import { SiteService } from '../../services/site.service';
import { SiteModel } from '../../models/site-model';
import { BaseComponent } from '../base.component';
import { DomSanitizer } from '@angular/platform-browser';
import { DateTime } from 'luxon';

@Component({
selector: 'app-site',
templateUrl: './site.component.html',
styleUrls: ['./site.component.css','../../../vizuly/lib/styles/vizuly.css']
})

export class SiteComponent extends BaseComponent implements OnInit, AfterViewInit {
siteHid;
scute_data;
window_narrow;
scute_data_ready: Boolean;
sticky: boolean = false;
elementPosition: any;

constructor(public sanitizer: DomSanitizer, private route: ActivatedRoute, protected router: Router, private authService: AuthService, private siteService: SiteService) {
super();
}

@ViewChild("stickyMenu", {read: ElementRef}) tr: ElementRef;

ngOnInit() {
this.route.paramMap.subscribe((params: ParamMap) => {
this.siteHid = params.get('siteHid');
this.loadSite(this.siteHid);
});
}

ngAfterViewInit(){
console.log(this.tr)
this.elementPosition = this.tr.nativeElement
// this.elementPosition = this.stickyMenu.nativeElement.offsetTop;
console.log(this.elementPosition) //undefined
}

@HostListener('window:scroll', ['$event'])
handleScroll() {
console.log(this.sticky, window.pageYOffset, this.elementPosition)
this.sticky = (window.pageYOffset >= this.elementPosition) ? true : false;
console.log(this.sticky)
}

loadSite(siteHid){
}

}

最佳答案

你在这里绑定(bind)了错误的属性:

[class.sticky] = "stickyMenu"

应该是

[class.sticky] = "sticky"

关于html - 在 Angular 6 中使用 @ViewChild 创建粘性元素 - 无法获取元素的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56119574/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com