ng-bootstrap 滚动间谍在没有高度的情况下无法工作?

问题描述 投票:0回答:1

我在我的项目中使用 ng-bootstrap

[ngbScrollSpy]
指令,如文档中所述,但它不起作用 - 滚动时活动项目不会改变。

我的代码如下:

<div>
    <div class="sticky-top">
        <ul class="nav menu-sidebar">
            <li >
                <a [ngbScrollSpyItem]="[spy, 'about']">About</a>
            </li>
            <li >
                <a [ngbScrollSpyItem]="spy" fragment="schedule">Schedule</a>
            </li>
            <li >
                <a [ngbScrollSpyItem]="spy" fragment="hotel">Information about the hotel</a>
            </li>
        </ul>
    </div>

    <div ngbScrollSpy #spy="ngbScrollSpy" >
        <section ngbScrollSpyFragment="about">
            <h3>About</h3>
            <p>{{some long long text and content}}</p>
        </section>
        <section ngbScrollSpyFragment="schedule">
            <h3>Schedule</h3>
            <p>{{some long long text and content}}</p>
        </section>
        <section ngbScrollSpyFragment="hotel">
            <h3>Information about the hotel</h3>
            <p>{{some long long text and content}}</p>
        </section>
    </div>
</div>

我在这个 stackoverflow 问题中看到,我的问题是我没有向我的 div 提供 height

,这是事实。

但我的滚动间谍部分遍布整个页面,而不是一个小 div,(导航本身是

sticky-top

)。所以我不能给它高度。

我知道有替代方法 - 刷新窗口滚动上的滚动间谍,但我没有找到可以帮助我的正确代码。

你能解决我的问题吗? 为我提供刷新滚动间谍的代码/给我有关高度的提示/帮助我找到另一个相应的元素。

非常感谢!

附上

stackblitz 演示的链接

angular ng-bootstrap scrollspy
1个回答
0
投票
注意:我使用来自

@ng-bootstrap/ng-bootstrap 的 NgbScrollSpy (我想它是非常相似的库)

我做什么:

我将所有内容(包括导航)包装在

<div class="wrapper" ngbScrollSpy #spy="ngbScrollSpy" rootMargin="2px" [threshold]="1.0" > <div class="sticky-top pt-4 pb-4 bg-white"> ..here the navigation... </div> ..here the sections... <section ngbScrollSpyFragment="about"> </section> //the last I use margin-bottom:2rem; <section ngbScrollSpyFragment="hotel" style="margin-bottom:10rem" </section> </div>
见“门槛”。这表明“更改”活动片段应该可见的百分比(1 是 100%)

包装类

.wrapper{ height:100%; position: absolute; top:0; }
我使用

强制链接的类别

//remove all the class for the link a{ color:black; text-decoration:none; padding:8px 16px; } a.custom-active{ color:white; background-color:royalblue }
以及我使用的每个链接

<a [class.custom-active]="spy.active=='about'">About</a>
嗯,问题是如何“滚动到”。 “链接”应该作为链接使用。

第一个是指示“路由器”应该考虑“碎片”

如果我们的组件是独立组件,我们需要使用提供者,provideRouter

bootstrapApplication(App, { providers: [ provideRouter([], withInMemoryScrolling({anchorScrolling:'enabled'})), ] })
然后,我们需要考虑到我们的页面确实没有

滚动,div“包装器”是谁拥有滚动。因此,我们订阅 router.events,当事件有“锚点”时,我们滚动“包装器”div constructor(router: Router) { router.events.pipe(filter((e:any) => e.anchor)).subscribe((e: any) => { (document.getElementById('wrapper') as any).scrollTop+= (document.getElementById(e.anchor)?.getBoundingClientRect().top||0) -72; //<--this is the offset }); }

在这个
stactblitz

中你有一个有效的例子

© www.soinside.com 2019 - 2024. All rights reserved.