【问题标题】:How to get the window width in blazor如何在 blazor 中获取窗口宽度
【发布时间】:2020-02-27 00:07:43
【问题描述】:

我正在尝试获取响应式内容的窗口宽度。 谢谢!

我试过了 @code{ public WindowState State { get; set; } = WindowState.Default;}

`@code{private Window myWindow = ?}`

【问题讨论】:

  • 使用 JS interopt 来做到这一点
  • 您可能想查找 Ed Charbeneau 的名为 BlazorSize 的 nuget 包
  • 我在Blagario上使用JS Interop的唯一部分

标签: blazor


【解决方案1】:

查看此链接以获取教程 https://blazor.tips/blazor-how-to-ready-window-dimensions/

基本上你需要注册 IJSRuntime 来调用一个 JS getDimensions() 函数

using Microsoft.JSInterop;
using System.Threading.Tasks;

public class BrowserService
{
    private readonly IJSRuntime _js;

    public BrowserService(IJSRuntime js)
    {
        _js = js;
    }

    public async Task<BrowserDimension> GetDimensions()
    {
        return await _js.InvokeAsync<BrowserDimension>("getDimensions");
    }

}

public class BrowserDimension
{
    public int Width { get; set; }
    public int Height { get; set; }
}

JS 细节

<script type="text/javascript">
    window.getDimensions = function() {
        return {
                width: window.innerWidth,
                height: window.innerHeight
            };
    };
</script>

【讨论】:

  • 如果 JavaScript 函数 getDimensions 不可用,因为您已导航到另一个 Blazor 页面(在 Blazor WASM 中),然后将您的 JavaScript 函数放在单独的文件中,例如getDimensions.js,并动态加载它,例如public async Task GetDimensions() { await JsRuntime.InvokeAsync("import", "getDimensions.js"); return await _js.InvokeAsync("getDimensions"); }
【解决方案2】:

创建一个 JavaScript 文件,例如脚本/getwindowsize.js:

export function getWindowSize()
{
    return {
        width: window.innerWidth,
        height: window.innerHeight
    };
};

在您的 .razor 文件中:

@inject IJSRuntime JsRuntime

Displaly the Window size: @windowWidth, @windowHeight
<button class="btn btn-primary" @onclick="OnButtonClick">Get Dimensions</button>

@code {
    private IJSObjectReference jsModule;

    public int windowHeight, windowWidth;

    public class WindowDimensions
    {
        public int Width { get; set; }
        public int Height { get; set; }
    }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            jsModule = await JsRuntime.InvokeAsync<IJSObjectReference>("import", "./scripts/getwindowsize.js");
        }
    }

    private async Task OnButtonClick()
    {
        var dimension = await jsModule.InvokeAsync<WindowDimensions>("getWindowSize");
        windowHeight = dimension.Height;
        windowWidth = dimension.Width;
    }

}

如果您更改了 getwindowsize.js 的内容(例如,如果您使用了先前答案或网站中的答案),请不要忘记告诉您浏览器进行硬重新加载并清空缓存。

这适用于 Blazor WebAssembly、.Net Core 5。

【讨论】:

    猜你喜欢
    • 2012-01-21
    • 2019-10-03
    • 2011-01-05
    • 2014-05-20
    • 1970-01-01
    • 2016-06-02
    • 1970-01-01
    • 2021-10-27
    • 2010-10-11
    相关资源
    最近更新 更多