You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET MAUI Blazor页面内导航实现方案咨询

.NET MAUI Blazor 页面内锚点跳转实现方案

原生实现方案

普通HTML锚点标签(<a href="#id">)无法直接生效,原因是Blazor的单页路由机制结合MAUI WebView的特性,默认不会触发原生锚点滚动。以下是两种原生解决思路:

1. JS互操作直接滚动到元素

通过Blazor的JS互调用能力,直接操作DOM实现滚动:

  • 第一步:在wwwroot/index.html中添加全局JS函数:
window.scrollToElement = (elementId) => {
    const target = document.getElementById(elementId);
    if (target) {
        target.scrollIntoView({ behavior: 'smooth', block: 'start' });
    }
};
  • 第二步:在Blazor组件中注入IJSRuntime,通过按钮或自定义事件触发滚动:
@inject IJSRuntime JSRuntime

<button @onclick="() => ScrollTo('target-section')">跳转到目标区域</button>

<div id="target-section" style="margin-top: 1200px; padding: 20px;">
    这里是目标锚点区域内容
</div>

@code {
    private async Task ScrollTo(string elementId)
    {
        await JSRuntime.InvokeVoidAsync("scrollToElement", elementId);
    }
}

2. 结合NavigationManager监听哈希变化

利用Blazor的路由哈希机制,配合JS实现自动滚动:

  • 第一步:在wwwroot/index.html中添加JS函数:
window.handleHashScroll = () => {
    const hash = window.location.hash.substring(1);
    if (hash) {
        const target = document.getElementById(hash);
        target?.scrollIntoView({ behavior: 'smooth' });
    }
};
  • 第二步:在组件中注入NavigationManager,订阅路由变化事件:
@inject NavigationManager NavManager
@implements IDisposable

<a href="#about-section">跳转到关于我们</a>

<div id="about-section" style="margin-top: 1200px; padding: 20px;">
    关于我们区域内容
</div>

@code {
    protected override void OnInitialized()
    {
        NavManager.LocationChanged += OnLocationChanged;
        // 页面加载时如果有哈希,立即触发滚动
        _ = JSRuntime.InvokeVoidAsync("handleHashScroll");
    }

    private async void OnLocationChanged(object? sender, LocationChangedEventArgs e)
    {
        await JSRuntime.InvokeVoidAsync("handleHashScroll");
    }

    public void Dispose()
    {
        NavManager.LocationChanged -= OnLocationChanged;
    }
}

第三方组件方案(Blazorise)

如果不想手动写JS逻辑,可以使用Blazorise组件库的内置滚动功能:

  1. 安装Blazorise.Maui包:
dotnet add package Blazorise.Maui
  1. 在MauiProgram.cs中配置Blazorise服务:
using Blazorise;
using Blazorise.Bootstrap;
using Blazorise.Icons.FontAwesome;

builder.Services.AddBlazorise(options =>
{
    options.Immediate = true;
})
.AddBootstrapProviders()
.AddFontAwesomeIcons();
  1. 在组件中使用Blazorise的Div组件和引用实现滚动:
@using Blazorise

<Button Click="@(() => TargetSection.ScrollTo())">跳转到服务介绍</Button>

<Div @ref="TargetSection" Style="margin-top: 1200px; padding: 20px;">
    服务介绍区域内容
</Div>

@code {
    private Div TargetSection { get; set; }
}

内容的提问来源于stack exchange,提问作者Rob White

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 01:50:32