首页 > 解决方案 > Javascript Keydown 未触发

问题描述

我需要帮助来触发向上箭头的按键。我真的不明白这是什么问题,很可能是我凌乱的格式,但是keydown不会触发。

<script>
  window.addEventListener('keyup', (event) => {
    if (event.key == 'ArrowUp') {
        close();
    window.open("https://bsd.instructure.com/?login_success=1");
    }
});
</script>

标签: javascripthtml

解决方案


查看window.close()window.open()API。

如果浏览器阻止它们,JavaScript 将无法打开它们。我尝试了您的代码,它显示:
“Firefox 阻止此站点打开弹出窗口。[选项]”。

您只能打开用户生成的窗口(例如按钮/链接点击)。
您的活动运行良好,但浏览器阻止了弹出窗口。

window.addEventListener('keyup', (event) => {
  if (event.key == 'ArrowUp') {
    window.close(); // Blocked for certain standards
    window.open("https://bsd.instructure.com/?login_success=1"); // Blocked in the user's preferences
  }
});

我还建议您使用document事件而不是window

document.addEventListener('keyup', (event) => {
  if (event.key == 'ArrowUp') {
    // Action here
  }
});

您可以使用 windowlocation属性导航到页面。

document.addEventListener('keyup', (event) => {
  if (event.key == 'ArrowUp') {
    window.close();
    window.location.replace("https://bsd.instructure.com/?login_success=1");
  }
});


推荐阅读