c# - Blazor WASM 滚动事件未触发
问题描述
我正在使用最新版本Blazor WASM
并试图在滚动时为我的导航栏设置动画,但该onscroll
事件根本没有触发。
我已经在我的应用程序的不同位置尝试了该@onscroll
事件Blazor
以及本机onscroll
事件,但都不起作用。我也尝试JSInterop
订阅,window.onscroll
但它也不起作用。我唯一要工作的是@onwheel
来自的事件Blazor
,但这不适用于其他类型的滚动。
这是目前根本不支持Blazor
还是我做错了什么?
解决方案
在本文档中,@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>
推荐阅读
- vault - 我们如何将 Vault 数据从一台服务器导出到另一台服务器?
- python - FileNotFoundError: [Errno 2] 没有这样的文件或目录(即使它给出了目录中确切文件的名称)
- python - 从不同目录导入文件
- azure - 如何配置 log4j2 以记录到应用程序洞察力?
- javascript - TypeError:无法读取未定义的属性(读取“地图”)React JS
- javascript - 材质 Ui、MUI、Dialog、ScrollTop
- html - 在标题按钮上添加滚动到下一节链接,固定在 div 的底部
- r - 计算 R (dplyr) 中数据帧中每行字符串值的出现次数
- sparql - C/C++ 中的远程 SPARQL 查询
- ansible - 如何使用 Ansible 管理公共网络上的 Endnodes 的配置?