我尝试在 Blazor 上编写一个简单的蛇游戏,但找不到任何方法将我的事件绑定到文档上。
有机会在不同元素上绑定事件,例如div或input。
例如像:<input onkeypress="@KeyPressInDiv"/>
在哪里public void KeyPressInDiv(UIKeyboardEventArgs ev)
{....}
,我想,应该有一定的类比JavaScript方法document.onkeydown = function (evt) {}
我已经找到了几种方法解决此问题的工作:
1)使用JS绑定和调用blazor代码(摘自https://github.com/ aesalazar/AsteroidsWasm )
document.onkeydown = function (evt) {
evt = evt || window.event;
DotNet.invokeMethodAsync('Test.ClientSide', 'JsKeyDown', evt.keyCode);
//Prevent all but F5 and F12
if (evt.keyCode !== 116 && evt.keyCode !== 123)
evt.preventDefault();
};
document.onkeyup = function (evt) {
evt = evt || window.event;
DotNet.invokeMethodAsync('Test.ClientSide', 'JsKeyUp', evt.keyCode);
//Prevent all but F5 and F12
if (evt.keyCode !== 116 …Run Code Online (Sandbox Code Playgroud)