【问题标题】:How to add a key event handler that listens for the Space key?如何添加监听 Space 键的键事件处理程序?
【发布时间】:2015-02-04 09:58:55
【问题描述】:

如果用户按下回车键(并且按钮处于焦点),则按钮打开。但是当用户按下空格按钮时,我也想打开链接按钮。

预计将使用 Space 键触发按钮,而预计将通过 Enter 键触发链接。换句话说,当链接被用作按钮时,仅添加 role="button" 是不够的。为了与本机按钮保持一致,还需要添加一个按键事件处理程序来侦听 Space 键。
该怎么做?

  <a tabindex="0" title="Show project filter" class="button button-image img-button-select" role="button" aria-disabled="false" aria-controls="divFilterDetails" href="#"></a>

【问题讨论】:

  • 用户是否可以在网页中“到处”键入空格来触发此链接?链接的行为是什么?重定向?处理数据?
  • 只有当链接按钮处于焦点时,用户才能键入空格。链接例如打开带有一些数据的弹出窗口。

标签: javascript html


【解决方案1】:

您应该为此使用keypress 事件。示例here

【讨论】:

    【解决方案2】:

    我找到了解决方案。

        $(document).ready(function () {
            //Add keypress event on every link where exist role="button"
            $(document).on('keypress', 'a[role="button"]', null, onKeypressButton, false);
        });
    
    
    function onKeypressButton(e) {
        //Need both, 'keyCode' and 'which' to work in all browsers.
        var code = e.keyCode || e.which,
            spaceKey = 32;
        //If user press space key:
        if (code == spaceKey) {
            //Do same thing as onclick:
            $(e.currentTarget).click();
            e.preventDefault();
            e.stopImmediatePropagation();
       }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-06
      • 2018-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-22
      相关资源
      最近更新 更多