admin 管理员组文章数量: 1086019
I am using Blazor and need to detect when the user scrolls the page... (if possiable i rather do this without JS but I dont see anyway)
for refecence I am trying to create similar menu effect: /
Main Issue document.body.addEventListener("scroll", function ()
doesnt get trigger
In JavaScript, this is very simple to do, but I'm having a hard time figuring out how to achieve this in Blazor. I've tried using JavaScript interop, but I'm not sure if I'm implementing it correctly. Can anyone help me with the right approach for detecting scroll events in Blazor and reacting to them, especially for a navbar class change based on scroll position?
Debugging: initializeScroll(dotNetHelper)
function runs successfully, but the document.body.addEventListener("scroll", function () {
part does not seem to trigger. I can see that the JavaScript function is being called, but the scroll event listener is not firing as expected.
my best guess: . I think issue is that Nav doesn't have scroll. I should be using scroll on body maybe?
MainLayout.razor
@inherits LayoutComponentBase
@inject NavigationManager NavigationManager
<div class="page">
@using Microsoft.AspNetCore.Components
<main>
<TopNavMenu />
<div>
@Body
</div>
<Footer/>
</main>
</div>
TopNavManu.razor
@implements IAsyncDisposable
@inject IJSRuntime JS
@rendermode InteractiveServer
<AuthorizeView>
<NotAuthorized>
<!-- Full Width Navbar using Bootstrap 5.3.2 -->
<nav id="myNavBar" class="navbar_Top navbar fixed-top navbar-expand-lg w-100 @navbarClass">
...
</nav>
</NotAuthorized>
</AuthorizeView>
@code {
private string navbarClass = ""; // Start with no class
private IJSObjectReference? jsModule;
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
jsModule = await JS.InvokeAsync<IJSObjectReference>("import",
"/Components/Layout/TopNavMenu.razor.js");
await jsModule.InvokeVoidAsync("initializeScroll");
}
}
[JSInvokable]
public void OnScrollChanged(bool isScrolledDown)
{
Console.WriteLine($"OnScrollChanged invoked: {isScrolledDown}");
navbarClass = isScrolledDown ? "navbarbg" : "";
StateHasChanged(); // Notify Blazor to update UI
}
public async ValueTask DisposeAsync()
{
if (jsModule is not null)
{
await jsModule.DisposeAsync();
}
}
TopNavMenu.razor.js
export function initializeScroll(dotNetHelper) {
alert('initializeScroll');
console.log("initializeScroll");
document.body.addEventListener("scroll", function () {
alert('addEventListener');
console.log("addEventListener");
});
}
本文标签: javascriptDetecting Scroll in Blazor and Reacting to Scroll PositionStack Overflow
版权声明:本文标题:javascript - Detecting Scroll in Blazor and Reacting to Scroll Position - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://roclinux.cn/p/1744029384a2521218.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论