创建键盘导航,遇到以下问题:
let currentActive = document.activeElement;
if (e.key === "ArrowLeft") {
currentActive.previousElementSibling.focus();
}
代码按预期工作,但 TypeScript 提示 Property 'focus' does not exist on 'Element'?
- currentActive
是 <img />
标签。
我尝试将 currentActive 指定为 HTMLElement,方法如下:
let currentActive = document.activeElement as HTMLCollectionOf<HTMLElement>
,但似乎不那么喜欢。
我错过了什么?
最佳答案
我建议尝试这样的事情:
let currentActive = document.activeElement;
if (e.key === "ArrowLeft") {
(currentActive.previousElementSibling as HTMLElement)?.focus();
}
请注意,自 TypeScript 3.7 起可选链可用
关于javascript - 'focus' 上不存在属性 'Element' ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59614647/