【问题标题】:Blazor WASM scroll event not firingBlazor WASM 滚动事件未触发
【发布时间】:2021-03-03 22:32:43
【问题描述】:

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

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

目前Blazor 不支持此功能还是我做错了什么?

【问题讨论】:

    标签: c# .net asp.net-core blazor blazor-webassembly


    【解决方案1】:

    在这个document, @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>
    

    【讨论】:

    • 修改了js部分来监听文档本身,但是这个答案对我有用,谢谢!
    猜你喜欢
    • 2020-01-31
    • 2020-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多