我正在尝试使用 JSinterop,但它似乎不起作用。
我正在尝试使用此代码笔示例实现返回顶部按钮 https://codepen.io/rdallaire/pen/apoyx
我已将 CSS 和 Javascript 文件添加到主机文件中。加载站点时,它们会显示在屏幕上。但该按钮从未出现在我的屏幕上。
不得不稍微调整一下 JS 以便它可以被 JsInterop 调用
√ Built build\app....
已添加到我的页面
// ===== Scroll to Top ====
function scrollToTopFunc() {
$(window).scroll(function() {
if ($(this).scrollTop() >= 50) { // If page is scrolled more than 50px
$('#return-to-top').fadeIn(200); // Fade in the arrow
} else {
$('#return-to-top').fadeOut(200); // Else fade out the arrow
}
});
$('#return-to-top').click(function() { // When arrow is clicked
$('body,html').animate({
scrollTop: 0 // Scroll to top of body
},
500);
});
}
以及对 javascript 的调用
@inject IJSRuntime JS;
并将标签添加到页面
protected override async Task OnAfterRenderAsync(bool firstRender)
{
await JS.InvokeVoidAsync("scrollToTopFunc");
}
现在当我加载页面时,我在谷歌开发工具中没有发现错误。真的很迷茫。谁能指出我正确的方向?
答案 0 :(得分:2)
如果您需要在 blazor 服务器应用程序中使用 javascript(.js) 文件,
1.在 wwwroot 文件夹中创建您的 javascript 文件。 例如:Javascript.js:
window.JsInteropFunction = (ctrl) => {
// Your code
};
2.在_Host.cshtml文件(head标签)中引用该.js文件。
<head>
<script src="~/Javascript.js"></script>
</head>
3.在你的razor文件中注入IJSruntime
@inject IJSRuntime JSRuntime;
@code{
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if(firstRender){
await JSRuntime.invokevoidasync("JsInteropFunction", { "TestID" },true);
statehaschanged();
}
}
}
答案 1 :(得分:0)
我最终通过执行以下操作在不使用 javascript 文件的情况下实现了这一点
我只是将我的标题用 id="Main" 包裹在一个 div 中,这份工作做得很好。