首页 > 解决方案 > Blazor WASM 滚动事件未触发

问题描述

我正在使用最新版本Blazor WASM并试图在滚动时为我的导航栏设置动画,但该onscroll事件根本没有触发。

我已经在我的应用程序的不同位置尝试了该@onscroll事件Blazor以及本机onscroll事件,但都不起作用。我也尝试JSInterop订阅,window.onscroll但它也不起作用。我唯一要工作的是@onwheel来自的事件Blazor,但这不适用于其他类型的滚动。

这是目前根本不支持Blazor还是我做错了什么?

标签: c#.netasp.net-coreblazorblazor-webassembly

解决方案


在本文档中,@onscroll不建议使用事件来处理滚动。因为它可能会损害 UI 响应能力或消耗过多的 CPU 时间。因此,您可能更喜欢使用 JS 互操作来注册触发频率较低的回调。

例如,在 div 中添加一个 ElementReference。Index.razor 中的这段代码。

@inject IJSRuntime JS
@implements IDisposable

<div @ref="scrollElement" style="border:1px dashed red;height:100px;width:200px;overflow:auto">
In my younger and more vulnerable years my father gave me some advice that I've been turning over in my mind ever since.
<br><br>
'Whenever you feel like criticizing anyone,' he told me, just remember that all the people in this world haven't had the advantages that you've had.'
</div>

@code {
  ElementReference scrollElement;

  DotNetObjectReference<Index> selfReference;

  protected override async Task OnAfterRenderAsync(bool firstRender)
  {
    if (firstRender)
    {
        selfReference = DotNetObjectReference.Create(this);
        var minInterval = 500; // Only notify every 500 ms
        await JS.InvokeVoidAsync("onDivScroll",
            scrollElement, minInterval);
    }
  }

  public void Dispose() => selfReference?.Dispose();
}

创建一个 JavaScript 文件。

function onDivScroll(elem, interval) {
  elem.addEventListener('scroll', function(e) {
      console.log(e)
  }, interval);
}

然后在 _Index.html 中引用它。

<script src="./filename.js"></script>

在此处输入图像描述


推荐阅读