javascript - 在 DIV 上按下按键以引用某个位置

标签 javascript html location-href

我知道如何让 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 文件

最佳答案

只需将两个监听器附加到 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>

A live demo at jsFiddle .

关于javascript - 在 DIV 上按下按键以引用某个位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20920193/

相关文章:

javascript - 没有setTimeout的vue点击动画

html - 如何在网页中正确设置iframe

javascript - window.location.hash 始终返回前一个哈希值,而不是当前哈希值

javascript - 使用 Javascript onClick 事件转到子元素的 href

Javascript 四舍五入到所需的小数位数问题

javascript - 有条件地加载 javascript(外部和内部)并保持执行顺序

javascript - 使用默认的 .sort() 对 JavaScript 中所需的数组对象进行排序

html - 是什么导致使用 960 网格系统的 div 中出现额外空间和随机对齐?

javascript - 使用 addClass 显示间隔

javascript - jQuery动态改变onclick位置.href