0

我知道如何让 div 在单击时引用一个位置

<div onclick="location.href='newurl.html';" tabindex="0"><a>Text</a></div>

但它只在鼠标单击时起作用,但如果我想通过键盘导航并按“Enter 键”或“空格键”它就不起作用..

所以我想要的是这样的

<div onkeydown="location.href='newurl.html';" tabindex="0"><a>Islam</a></div>

我不想在其他地方写代码,比如 js 文件

4

2 回答 2

2

只需将两个侦听器都附加到div, 并onkeydown检查按下的键:

<div
  onkeydown="if(event.which===32||event.which===13) location.href='newurl.html';"
  onclick="location.href='newurl.html';"
  tabindex="0"
>
    <a>Islam</a>
</div>

jsFiddle 的现场演示

于 2014-01-04T11:34:20.690 回答
1

我不完全确定你想要什么,但也许你正在寻找event.keyCode。它为您提供了一个按键代码,您可以轻松检查EnterSpace

<div onkeydown="if(event.keyCode==13||event.keyCode==32)location.href='newurl.html'; " onclick="location.href='newurl.html';" tabindex="0">Link</div>
于 2014-01-04T12:01:19.147 回答