用于处理Tab键按下的JavaScript

bha*_*esh 19 javascript

众所周知,当我们点击TAB键盘上的键时,它允许我们浏览当前打开的网页上的所有活动的href链接.是否可以通过JavaScript读取这些网址?

例:

function checkTabPress(key_val) {
    if (event.keyCode == 9) {
        // Here read the active selected link.
    }
}
Run Code Online (Sandbox Code Playgroud)

Sum*_*ai8 10

您应该可以使用keyup事件执行此操作.具体而言,event.target应指向所选元素,event.target.href并为您提供该元素的href值.有关更多信息,请参阅mdn.

下面的代码是jQuery,但除了样板代码之外,其余代码在纯javascript中是相同的.这是keyup绑定到每个链接标记的处理程序.

$('a').on( 'keyup', function( e ) {
    if( e.which == 9 ) {
        console.log( e.target.href );
    }
} );
Run Code Online (Sandbox Code Playgroud)

jsFiddle:http://jsfiddle.net/4PqUF/


uKo*_*lka 9

有以下html:

<!-- note that not all browsers focus on links when Tab is pressed -->
<a href="http://example.com">Link</a>

<input type="text" placeholder="Some input" />
<a href="http://example.com">Another Link</a>

<textarea>...</textarea>
Run Code Online (Sandbox Code Playgroud)

您可以通过以下方式进入活动链接:

// event listener for keyup
function checkTabPress(e) {
    "use strict";
    // pick passed event or global event object if passed one is empty
    e = e || event;
    var activeElement;
    if (e.keyCode == 9) {
        // Here read the active selected link.
        activeElement = document.activeElement;
        // If HTML element is an anchor <a>
        if (activeElement.tagName.toLowerCase() == 'a')
            // get it's hyperlink
            alert(activeElement.href);
    }
}

var body = document.querySelector('body');
body.addEventListener('keyup', checkTabPress);
Run Code Online (Sandbox Code Playgroud)

这是一个有效的例子.